Upload image with ajax, HttpPostedFileBase is null Mvc Asp
本问题已经有最佳答案,请猛点这里访问。
我必须在提交表格前上传图片。所以我用Ajax来做。
这是我的帮助控制器:
1 2 3 4 5 | [HttpPost] public void AcceptUpload(HttpPostedFileBase TemporaryForLast, string ReferanceNo) { TemporaryForLast.SaveAs(Server.MapPath("~/Profiles/images/" + ReferanceNo +"/") +"HoldCopy" +".jpg"); } |
这是我的观点:
1 | <input id="HoldCopy" type="file" name="HoldCopy" accept="image/*"> |
ANS脚本:
1 2 3 4 5 6 7 8 9 10 | $("#acceptUpload").click(function () { var formData= new FormData(); var imagefile=document.getElementById("HoldCopy").files[0]; formData.append("imageFile",imageFile); var xhr = new XMLHttpRequest(); xhr.open("POST","/Help/AcceptUpload", true); xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false); xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false); xhr.send(formData); }); |
视图
您可以使用jquery-ajax代替jquery-ajax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | function SubmitButtonOnclick() { var formData= new FormData(); var imagefile=document.getElementById("imageFile").files[0]; formData.append("imageFile",imageFile); var xhr = new XMLHttpRequest(); xhr.open("POST","/Help/AcceptUpload", true); xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false); xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false); xhr.send(formData); } function UploadComplete(evt) { if (evt.target.status == 200) alert("Logo uploaded successfully."); else alert("Error Uploading File"); } function UploadFailed(evt) { alert("There was an error attempting to upload the file."); } |