繁体   English   中英

将文件(FormData)上载到WebApi

[英]Upload File (FormData) to WebApi

我正在尝试将文件上传到WebApi,但没有收到文件。 另外我也不知道文件是否被追加。 我正在这样做:

if (this.state.file) {
            var file = this.state.file;
            if (window.FormData !== undefined) {
                var data = new FormData();
                data.append("file", file);

                $.ajax({
                    type: "POST",
                    url: "/api/service/upload",
                    contentType: "text/csv",
                    processData: false,
                    data: data,
                    success: function (result) {
                        console.log(result);
                    },
                    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);
                    }
                });
            }
        }

另外,要检查我的请求有效负载的内容,我尝试了此方法,而不是Ajax调用:

                var xhr = new XMLHttpRequest;
                xhr.open('POST', '/', true);
                xhr.setRequestHeader('Content-Type', 'text/csv');
                xhr.send(data);

并且仅出现:

------ WebKitFormBoundary6xZnDkSOxBAxaovA Content-Disposition:表格数据; NAME = “文件”; filename =“ Teste.csv”内容类型:application / vnd.ms-excel

------ WebKitFormBoundary6xZnDkSOxBAxaovA--

如果文件大小不大,则可以使用base64编码。 将编码的字符串数据发送到Web api服务。 解码并使用它。

好的,您有一个文件对象,看起来不错。 尝试以下代码。

var file; // Assuming this is the file object.
var formData = new FormData();
formData.append('file', file);

$.ajax({
    type : 'POST',
    url : '/api/service/upload',
    data : formData,
    dataType : 'json', // json, html whatever you like.
    contentType: false, // Change this line
    processData: false
}).done(function(res) {
    console.log(res);
}).fail(function(res) {
    console.log(res.responseText);
});

如果您在api服务中使用PHP。 您应该可以使用print_r($_FILES)并在那里查看文件。

希望这可以帮助。

暂无
暂无

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

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