7

I must upload image before Form is submitted. So I used ajax to do it.

Here is my HelpController:

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

Here is my view:

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

Ans Script:

$("#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 functions are also updated.

1
  • 1
    Ajax don't support file upload. No one told you that?
    – Mat J
    Commented May 20, 2014 at 5:43

1 Answer 1

3

View

Instead of Jquery Ajax you could use

<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>
6
  • it gives an error ReferenceError: imageFile is not defined formData.append("imageFile", imageFile);
    – DSI
    Commented May 20, 2014 at 7:04
  • @BarsDS according to your code this line will change var imagefile=document.getElementById("HoldCopy").files[0]; Commented May 20, 2014 at 7:07
  • yes i have changed it, and this error appeared after i changed
    – DSI
    Commented May 20, 2014 at 7:09
  • can you update the code what you have done Commented May 20, 2014 at 7:15
  • it's very strange, but i resolve the problem by renaming imageFile to ImageFile. anyway i solve the problem with your help. thanks a lot Nilesh
    – DSI
    Commented May 20, 2014 at 8:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.