【问题标题】:Best practice for uploading and binding a model that has a file in ASP.NET Web Api上传和绑定在 ASP.NET Web Api 中有文件的模型的最佳实践
【发布时间】:2016-09-16 10:29:20
【问题描述】:

我正在为我的 Android 应用程序开发后端服务。后端使用ASP.NET Web Api开发。

现在我遇到了绑定我的模型的问题。我有一个User 模型,它具有典型字段,例如NameAge 等。目前我正在以 JSON 的形式将数据从应用程序发送到服务,它完美绑定到我的User 模型。

但是现在我需要在我的User 类中添加另一个字段,这是一个个人资料图片。我知道如果我将它们转换为字节数组,我可以通过 JSON 发送图像文件,但这是一个好方法吗?

我能想到的另一种方法是分别发送模型和图像文件。然后只需将图像的GUID 关联到User 模型的个人资料图像字段。但这也没有意义,因为图像文件上传明显User json 文件,所以当我收到 User json 并初始化一个新的 User 时,文件可能仍在上传,因此没有机会从中获取GUID

谁能为此提出一个好的设计?我相信这是涉及用户帐户管理的任何服务的一个非常常见的功能。一般是怎么做的?

【问题讨论】:

  • 我认为发送 byte[] 是更好的方法。
  • 您好,感谢您的评论。为什么要这么推荐?转换为字节数组不会增加大小吗?

标签: c# asp.net json asp.net-web-api model-binding


【解决方案1】:

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");        
    }
}

【讨论】:

  • 很抱歉,这并不能回答我的问题。我正在寻找一种将图像与我的用户模型、设计绑定在一起的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 2012-05-30
  • 2012-06-13
相关资源
最近更新 更多