簡體   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