简体   繁体   English

使用jQuery Ajax在Web Api中上传多个文件

[英]Multiple File Upload in Web Api using jQuery Ajax

I have a problem uploading files using jQuery Ajax and Web API. 我在使用jQuery Ajax和Web API上传文件时遇到问题。 When I make a POST to my API, I am not getting uploaded files in my controller. 当我对API进行POST时,我没有在控制器中上传文件。

In my HTML I have several file inputs with class="file" like this: 在我的HTML中,我有几个带有class =“ file”的文件输入,如下所示:

<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: 另外,我有一个执行Javascript函数的按钮:

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: 最后,在我的Web api控制器中,如果尝试访问HttpContext.Current.Request.Files,则会得到一个空集合,并且如果尝试访问如下内容:

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

Then I get this error: 然后我得到这个错误:

Invalid 'HttpContent' instance provided. 提供了无效的“ HttpContent”实例。 It does not have a content type header starting with 'multipart/'. 它没有以“ multipart /”开头的内容类型标头。 Parameter name: content 参数名称:内容

Thanks in advance. 提前致谢。

You are using API so your request is an HttpResponseMessage. 您正在使用API​​,因此您的请求是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 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. 如果确实有期限,建议您一次发布1个文件,并说明一次上传多个文件的局限性。 Otherwise use a third party API to learn from and reverse engineer it for yourself. 否则,请使用第三方API自行学习并进行反向工程。

I finally figured it out. 我终于弄明白了。

I changed my Ajax call as @guest271314 suggests to get all file inputs: 我更改了Ajax调用,因为@ guest271314建议获取所有文件输入:

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. 我仍然不知道如何在同一请求中接收JSON对象和文件(如果可能的话),但我拆分为2个不同的控制器,效果很好。

Thanks everyone for your help! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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