我在这里找到了这个 ajax 文件上传脚本 http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
应该为我的文件上传表单添加 ajax 功能
<div id="dialog" title="Upload Image">
<%
Html.BeginForm("Upload", "BugTracker", FormMethod.Post,new { id="uploadForm", enctype = "multipart/form-data"});
%>
Select a file: <input type="file" name="file" id="file" />
<h6>Upload a screenshot related to the ticket</h6>
<input type="submit" class="button" value="Upload" id="upload" onclick="uploadImage();" name="submit" />
<%Html.EndForm();%>
</div>
我已经设置了一个函数,当我的上传表单被提交时调用:
function uploadImage() {
var action = $("#uploadForm").attr('action');
$.ajaxFileUpload({
url: action,
secureuri: false,
fileElementId: 'file',
dataType: 'json',
success: function (data, status) {
$("#RelatedFileName").val() = data.FileName;
$("#dialog").dialog("close");
}
});
return false;
}
但它直接跳过成功回调函数,浏览器询问我是否要下载 json 文件。下面是我的上传操作:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
Regex imageFilenameRegex = new Regex(@"(.*?)\.(jpg|jpeg|png|gif)$");
if (file != null)
{
if (!imageFilenameRegex.IsMatch(file.FileName))
{
return JavaScript("alert('invalid file. you must upload a jpg, jpeg, png, or gif');");
}
else
{
string filePath = Path.Combine(HttpContext.Server.MapPath("~/Uploads"), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
return Json(new { FileName = "/Uploads/" + file.FileName });
}
}
else
{
return JavaScript("alert('seriously? select a file to upload before hitting the upload button.');");
}
}
我使用过 jQuery.post,它会触发 Controller 操作,但文件将为空,但至少会在它们的警告框中弹出错误,所以这就是我寻找另一个选项的原因。现在它触发 Controller 操作并上传文件,但它不处理任何响应。感谢您的帮助。
最佳答案
即使您传递的是 JSON,您使用的插件也需要 text/html
作为响应内容类型。所以如果你真的想使用它,你需要这样做:
return Content("{ FileName: '/Uploads/' }", "text/html");
如您所知,那是废话。
所以继续下载 jquery form plugin .它更容易使用。您不必在 HTML 中做任何事情,它完全不引人注目。只需在 javascript 中保持表单不变:
$(function() {
// Only indicate the form id, it will take care of reading the form action,
// returning false, ..., all you need is to concentrate
// on the success callback
$('#uploadForm').ajaxForm(function(result) {
alert(result);
});
});
另请注意,如果出现错误,您不应返回 Javascript。您始终需要从 Controller 操作中返回 Json。因此,如果出现错误:
return Json(new { errorMessage = "Kaboom", fileName = "" });
如果成功:
return Json(new { errorMessage = "", fileName = "/Uploads/" + file.FileName });
现在您可以通过检查返回的 JSON 对象的 errorMessage
属性来检查是否有错误:
$('#uploadForm').ajaxForm(function(result) {
if (result.errorMessage != '') {
alert(result.errorMessage);
} else {
$('#RelatedFileName').val(result.fileName);
$('#dialog').dialog('close');
}
});
关于javascript - mvc 中的 AJAX 上传脚本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983326/