简体   繁体   中英

MVC 4 Ajax Asynchronous File Upload Always Passing Null Value To Controller

I'm having a problem when trying to upload file asynchronously from ajax to my controller. I have 3 variables to pass (PictureId, PictureName, and PictureFile) . The problem lies on my "PictureFile" variable which should be holding the uploaded file itself but instead it always pass null value to the controller.

Here is my view model

public class PictureUpload
{
    public int PictureId { get; set; }
    public string PictureName { get; set; }
    public HttpPostedFileBase PictureFile { get; set; }
}

Here is my controller

public JsonResult EditPicture(PictureUpload picture)
{
    //do something here
}

Here is my form

<div class="thumbnail" id="uploadForm">
    <form name="uploadForm" enctype="multipart/form-data">
        <input type="text" name="fileId" hidden="hidden" />
        <input type="file" name="file" style="max-width: 100%" />
        <input type="button" name="cancel" value="cancel" />
        <span>
            <input type="button" name="upload" value="upload" />
        </span>
    </form>
</div> 

Here is my script

$("input[name=upload]").click(function () {
    var $pictureId = $("input[name=fileId]").val();
    var $pictureFile = $("input[name=file]").get(0).files[0];

    $.ajax({
        type: 'POST',
        url: '@Url.Action("EditPicture", "Restaurant")',
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify({ PictureId: $pictureId, PictureName: $pictureFile.name, PictureFile: $pictureFile }),
    });

In my controller parameter. "PictureId" and "PictureName" holds the correct value, but "PictureFile" is always null. So it means something is going just not right when the system passes the parameter from ajax to controller. Somehow the system treats "file" type differently from others. Could you help me so the file get passed successfully to the controller and tell me what is wrong with this approach?

As mentioned rightly in the comments use FormData. Below is a code snippet :

var fd = new FormData();
fd.append('file', fileObject);
fd.append('PictureId', pictureId);
fd.append('PictureName', pictureName);

    $.ajax({
        url: '/Restaurant/EditPicture',
        async: true,
        type: 'POST',
        data: fd,
        processData: false,
        contentType: false,
        success: function (response) {                  
        }
    });

You cannot upload files with AJAX. One way to achieve this is to use a hidden iframe which will simulate an AJAX call and perform the actual file upload or use Flash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM