我正在尝试使用 jquery 将文件传递给我的控制器,以便用户在上传后不必离开页面......
我似乎无法让它工作。一旦它传递给我的控制器,我就会不断获得“空引用”。这是我尝试过的:
控制器:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var image = Path.GetFileName(file.FileName);
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var filePath = Path.Combine(Server.MapPath("~/Content/Images/UploadedImages/"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(filePath);
return Json(filePath.ToString());
}
else
{
return Json("Image failed to load");
}
}
看法:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "testupload", name = "testupload" }))
{
<div class="editor-field">
<input type="file" name="file" id="file" />
</div>
<input type="submit" value="Submit"/>
}
<input type="button" onclick="upload();" value="Upload" />
<input type="text" id="url"/>
查询:
function upload() {
$.post("../../../Home/Upload", $("#testupload"), function (data) {
$("#url").val(data);
});
}