上传和绑定在 ASP.NET Web Api 中有文件的模型的最佳实践
Best practice for uploading and binding a model that has a file in ASP.NET Web Api
我正在为我的 Android 应用程序开发后端服务。后端在 ASP.NET Web Api.
中开发
现在我遇到了绑定我的模型的问题。我有一个 User
模型,它具有 Name
、Age
等典型字段。目前我正在以 [= 的形式从应用程序发送数据53=] 到服务,它与我的 User
模型完美绑定。
但是现在我需要在我的User
class中添加另一个字段,这是一个个人资料图片.我知道如果我将它们转换为字节数组,我可以通过 JSON 发送图像文件,但这是一个好方法吗?
我能想到的另一种方法是分开发送模型和图像文件。然后只需将图像的 GUID
关联到 User
模型的个人资料图像字段。但这也没有意义,因为图像文件上传显然 慢 比 User
json 文件,所以当我收到 User
json 并初始化一个新的 User
,文件可能仍在上传,因此 没有机会 从中获取 GUID
。
任何人都可以为此提出一个好的设计吗?我相信这是涉及用户帐户管理的任何服务的一个非常常见的功能。通常是怎么做的?
HTML
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
控制器
public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
我正在为我的 Android 应用程序开发后端服务。后端在 ASP.NET Web Api.
中开发现在我遇到了绑定我的模型的问题。我有一个 User
模型,它具有 Name
、Age
等典型字段。目前我正在以 [= 的形式从应用程序发送数据53=] 到服务,它与我的 User
模型完美绑定。
但是现在我需要在我的User
class中添加另一个字段,这是一个个人资料图片.我知道如果我将它们转换为字节数组,我可以通过 JSON 发送图像文件,但这是一个好方法吗?
我能想到的另一种方法是分开发送模型和图像文件。然后只需将图像的 GUID
关联到 User
模型的个人资料图像字段。但这也没有意义,因为图像文件上传显然 慢 比 User
json 文件,所以当我收到 User
json 并初始化一个新的 User
,文件可能仍在上传,因此 没有机会 从中获取 GUID
。
任何人都可以为此提出一个好的设计吗?我相信这是涉及用户帐户管理的任何服务的一个非常常见的功能。通常是怎么做的?
HTML
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
控制器
public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}