【问题标题】:Upload image with ajax, HttpPostedFileBase is null Mvc Asp [duplicate]使用ajax上传图像,HttpPostedFileBase为空Mvc Asp [重复]
【发布时间】:2014-07-08 01:12:32
【问题描述】:

我必须在提交表单之前上传图片。所以我用ajax来做。

这是我的帮助控制器:

[HttpPost]
public void AcceptUpload(HttpPostedFileBase TemporaryForLast, string ReferanceNo)
{
    TemporaryForLast.SaveAs(Server.MapPath("~/Profiles/images/" + ReferanceNo + "/") + "HoldCopy" + ".jpg");
}

这是我的看法:

<input id="HoldCopy" type="file" name="HoldCopy" accept="image/*">

Ans 脚本:

$("#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);
});

error 函数也更新了。

【问题讨论】:

  • Ajax 不支持文件上传。没人告诉你吗?

标签: jquery asp.net-mvc asp.net-mvc-4


【解决方案1】:

查看

你可以使用 Jquery Ajax 来代替

<script>
            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.");

    }
 </script>

【讨论】:

  • 它给出一个错误 ReferenceError: imageFile is not defined formData.append("imageFile", imageFile);
  • @BarsDS 根据您的代码,此行将更改 var imagefile=document.getElementById("HoldCopy").files[0];
  • 是的,我改了,改后出现这个错误
  • 你能更新你所做的代码吗
  • 这很奇怪,但我通过将 imageFile 重命名为 ImageFile 来解决问题。无论如何,我在你的帮助下解决了这个问题。非常感谢尼莱什
猜你喜欢
  • 2012-06-07
  • 2016-01-02
  • 2017-10-22
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
相关资源
最近更新 更多