【问题标题】:How to POST a file to asp.net mvc app? [duplicate]如何将文件发布到 asp.net mvc 应用程序? [复制]
【发布时间】:2013-12-12 13:47:49
【问题描述】:

我将一个简单的文本文件发布到一个 asp.net MVC 应用程序。当我使用下面的表单发布时,表单参数不为空。但是 file 是。任何想法我做错了什么?

<form method=post action="http://localhost/Home/ProcessIt" 
enctype="application/x-www-form-urlencoded"> 
<input type=file id="thefile" name="thefile" /> 
<input type="submit" name="Submit" /> 
</form>

在 asp.net mvc 应用中:

[HttpPost]
public ActionResult ProcessIt(FormCollection thefile)
{
  HttpPostedFileBase file = Request.Files["thefile"];
  ...
}

【问题讨论】:

  • 如果我使用HttpPostedFileBase,参数将为null。
  • 对输入元素和方法参数使用相同的名称。按照我发布的链接
  • 我已经更新了帖子。我对输入元素和方法参数使用相同的 ID/名称。还是没有文件。
  • 让它与 FormCollection 一起工作。 IE 正在缓存我的表单字段。刷新后,它就开始工作了。

标签: c# asp.net-mvc


【解决方案1】:

这对我有用:

查看:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

控制器:

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    // Verify that the user selected a file
    if (file != null && file.ContentLength > 0) 
    {
        // extract only the fielname
        var fileName = Path.GetFileName(file.FileName);

        // then save on the server...
        var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
        file.SaveAs(path);
    }
    // redirect back to the index action to show the form once again
    return RedirectToAction("Index");        
}

【讨论】:

【解决方案2】:

需要将enctype改为multipart/form-datahttp://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

【讨论】:

  • 文件仍为空。 Request.Files 集合中没有任何内容。
猜你喜欢
  • 1970-01-01
  • 2011-06-30
  • 2012-02-19
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多