Jos*_*Son 53 asp.net-mvc file-upload
我在ASP.NET MVC中上传文件时遇到问题.我的代码如下:
视图:
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index2</h2>
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" />
<input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)
控制器:
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
但uploadFile总是返回null.任何人都可以找出原因??
dot*_*tep 118
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index2</h2>
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="uploadFile"/>
<input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)
你必须提供姓名输入类型的文件,以uploadFile以模特在ASP.net MVC绑定工作,
还要确保您输入的文件类型和参数名的名字的HttpPostedFileBase是相同的.
我曾尝试过针对此主题在线发布的大部分解决方案,但发现使用解决方法更好.
我做了什么并不重要HttpPostedFileBase和/或HttpPostedFile总是为空.使用HttpContext.Request.Files集合似乎没有任何麻烦.
例如
if (HttpContext.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Request.Files[0];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath =(HttpContext.Server.MapPath("~/UploadedFiles") + httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(@"\")));
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中我只抓取第一个文件,但这只是循环通过集合保存所有文件的问题.
HTH
抢
小智 5
在我的场景中问题是id属性,我有这个:
<input type="file" name="file1" id="file1" />
Run Code Online (Sandbox Code Playgroud)
灵魂就是删除id:
<input type="file" name="file1" />
Run Code Online (Sandbox Code Playgroud)
虽然不是针对该特定用户的答案,但我想指出HTML 要求表单标记具有值为 multipart/form-data 的 enctype 属性。当然,属性及其值都必须正确。
对于mvc来说,这意味着在使用beginform时,应该使用带有htmlAttributes参数的版本
| 归档时间: |
|
| 查看次数: |
76041 次 |
| 最近记录: |