将文件(FormData)上载到WebApi

时间:2017-04-11 11:48:43

标签: javascript ajax asp.net-web-api file-upload

我正在尝试将文件上传到WebApi,但我没有收到该文件。此外,我不知道如果正在追加该文件。我这样做:

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

另外,要检查我的Request Payload的内容,我尝试了这个,而不是Ajax调用:

SHA1Bytes

只出现:

  

------ WebKitFormBoundary6xZnDkSOxBAxaovA Content-Disposition:form-data; NAME = “文件”; filename =“Teste.csv”内容类型:   应用/ vnd.ms-Excel中

     

------ WebKitFormBoundary6xZnDkSOxBAxaovA -

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

好的,你有一个文件对象,看起来是对的。试试下面的代码。

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)并在那里查看文件。

希望这有帮助。