简体   繁体   中英

Multiple File Upload in Web Api using jQuery Ajax

I have a problem uploading files using jQuery Ajax and Web API. When I make a POST to my API, I am not getting uploaded files in my controller.

In my HTML I have several file inputs with class="file" like this:

<form id="edit" enctype="multipart/form-data">
    <input class="file" type="file" name="field_custom_file" accept='image/*' />
    <input class="file" type="file" name="field_custom_file" accept='image/*' />
    <input class="file" type="file" name="field_custom_file" accept='image/*' />
</form>

In addittion, I have a button which executes a Javascript function:

function send() {
    var files = $('.file')[0].files;
    if (files.length > 0) {
        if (window.FormData !== undefined) {
            var data = new FormData();
            for (var x = 0; x < files.length; x++) {
                data.append("file" + x, files[x]);
            }

            $.ajax({
                type: "POST",
                url: '/api/tripgroups',
                contentType: false,
                processData: false,
                data: data,
                success: function (result) {
                    toastr.success('Trip Group was updated!');
                },
                error: function (xhr, status, p3, p4) {
                    var err = "Error " + " " + status + " " + p3 + " " + p4;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).Message;
                    console.log(err);
                },
                enctype: 'multipart/form-data',
                headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
            });
        } else {
            alert("This browser doesn't support HTML5 file uploads!");
        }
    }
}

Finally, in my web api controller, if I try to access HttpContext.Current.Request.Files I get an empty collection, and if I try to access content like this:

var streamProvider = new MultipartFormDataStreamProvider("images");
await Request.Content.ReadAsMultipartAsync(streamProvider);

Then I get this error:

Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'. Parameter name: content

Thanks in advance.

You are using API so your request is an HttpResponseMessage.

If you are not in a hurry I would suggest absorbing this article. http://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2

If you are indeed on a deadline, I would suggest posting 1 file at a time and explain the limitations of uploading many files at once. Otherwise use a third party API to learn from and reverse engineer it for yourself.

I finally figured it out.

I changed my Ajax call as @guest271314 suggests to get all file inputs:

var files = $('.file');
if (files.length > 0) {
    if (window.FormData !== undefined) {
        var data = new FormData();
        for (var x = 0; x < files.length; x++) {
            data.append("file" + x, files[x].files[0]);
        }
         $.ajax({
            type: "POST",
            url: '/api/tripgroups',
            contentType: false,
            processData: false,
            data: data,
            success: function (result) {
                toastr.success('Trip Group was updated!');
            }
        });
    } else {
        alert("This browser doesn't support HTML5 file uploads!");
    }
}

And the main issue was on my controller, because I had another parameter

public async Task<HttpResponseMessage> Post(SomeClass param)

when I removed that parameter it receives files correctly.

I still don't know how to receive a JSON object and files in the same request (if it is possible) but I split out into 2 different controllers and works well.

Thanks everyone for your help!

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