【发布时间】:2014-07-11 16:50:22
【问题描述】:
我在这里找到了这个 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,它会触发控制器操作,但文件将为空,但至少在它们的警报框中会弹出错误,所以这就是我寻找另一个选项的原因。现在它触发了控制器操作并且文件被上传,但它没有处理任何响应。任何帮助表示赞赏。
【问题讨论】:
标签: javascript jquery ajax asp.net-mvc-2