【发布时间】:2015-01-15 14:28:09
【问题描述】:
我想使用 MVC 和 jQuery 进行文件上传,但我的参数为空。在我的 jQuery 中,我获取表单数据并为其分配一个变量,然后将其发布到 ActionResult。我的参数为空,我不确定我是否正确传递数据。
HTML
<table>
<tr>
<td><img src="@Url.Content("~/AMTImages/UserAvatar.png")" width="64" height="64" style="border: thin solid" /></td>
<td></td>
<td></td>
<td>
<form enctype="multipart/form-data" id="imageUploadForm">
<table>
<tr>
<td>@Html.LabelFor(m => m.DisplayName, "Display Name: ")</td>
<td style="padding-left: 10px;">@Html.TextBoxFor(m => m.DisplayName)</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.UserImage, "User Image: ")</td>
<td style="padding-left: 10px; float: right;">@Html.TextBoxFor(m => m.UserImage, new { type = "file", accept = "image/*" })</td>
</tr>
</table>
</form>
</td>
<td>
<table style="display:none;">
<tr>
<td>
<progress></progress>
</td>
</tr>
</table>
</td>
</tr>
</table>
JavaScript
$(':file').change(function () {
var file = this.files[0];
$.ajax({
url: '@Url.Action("UploadImage", "User")', //Server script to process data
type: 'POST',
data: file,
beforeSend: function() {
},
success: function () {
},
error: function () {
},
processData: false,
contentType: file.type
});
});
操作结果
public ActionResult UploadImage(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Images"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View();
}
【问题讨论】:
-
@Rory McCrossan - 我的帖子是关于 ASP.NET MVC 的,这个答案只显示客户端代码。
-
没错。这里的问题是由于您的客户端代码,解决方案与我链接到的问题相同。
标签: jquery asp.net-mvc-5 image-uploading