2017-04-11 170 views
0

我想上传文件到WebApi,但我没有收到文件。此外,我不知道如果该文件正在追加。此外上传文件(FormData)到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内容处理:form-data; NAME = “文件”;文件名= “Teste.csv” 内容类型: 应用程序/ vnd.ms - Excel中

------ WebKitFormBoundary6xZnDkSOxBAxaovA--

+0

尝试从ajax调用中去除'contentType'选项。而且,请验证'this.state.file'是一个文件对象而不是文件对象的数组。 'console.log'。 – TipuZaynSultan

+0

我得到这个(我猜是一个文件对象): File {name:“Teste.csv”,lastModified:1491903259490,lastModifiedDate:2017年4月11日上午10:34:19 GMT + 0100(GMT Daylight Time),webkitRelativePath: “”,尺寸:32 ...} 上次更改 : lastModifiedDate : 星期二2017年4月11日10点34分19秒GMT + 0100(GMT夏令时间) 名 : “Teste.csv” 大小 : 类型 : “application/vnd.ms-excel” webkitRelativePath : “” __proto__ : 文件 –

+0

但是,我追加到FormData对象的文件后,该对象只有原型,是否正常?里面不应该有一个File对象? –

回答

0

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

+0

我如何获取并编码文件的内容? –

+0

基本示例[this](http://jsfiddle.net/eliseosoto/JHQnk/)。 – daylight

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

希望这会有所帮助。

相关问题