我在这里找到了这个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 ,它会触发控制器操作,但文件将为空,但至少会在警报框中弹出错误,所以这就是我寻找另一个选项的原因。现在它点击控制器操作并且文件被上传,但它不处理任何响应。任何帮助表示赞赏。