2

我需要通過的multipart/form-data的一些元信息像這樣一起上傳文件:文件上傳Angular2通過的multipart/form-data的,400錯誤

Header 
----boundary 
Meta 
----boundary 
File 
----boundary 

出於某種原因,我總是得到400錯誤,後端服務器告訴我,缺少Meta -Field。但是,如果我使用Wireshark查看Hex/Ascii轉儲,則該字段肯定存在。
下面捲曲命令運行完美,在文件被成功上傳:

curl -H "Expect:" -v -i -X POST -H "Content-Type: multipart/form-data" -H "Authorization: "token" -F "[email protected]/location" -F 'Meta={"access":"token"}' http://path 

因此,這似乎並沒有成爲一個後端的失敗。我的Angular(4.1.3)請求必須是壞的,但我無法弄清楚它有什麼問題。

模板的代碼:

<input #file_input type="file" (change)="onFileInputChange($event)" multiple> 

Angular2碼:

onFileInputChange(event) { 
    let fileList: FileList = event.target.files; 
    for (let i = 0; i < fileList.length; i++) { 
    let fp: File = fileList[i]; 
    let formData: FormData = new FormData(); 
    formData.append('File', fp, fp.name); 
    const body = JSON.stringify({ 
     'access': "token" 
    }); 
    this.formData.append('Meta', body); 
    let RequestHeader = new Headers(); 
    // auto set content type 
    RequestHeader.append('Content-Type', ''); 
    RequestHeader.append('Accept', 'application/json'); 
    RequestHeader.append('Authorization', "token"); 

    this.http.post(this.backend_url, formData, RequestHeader).map(
    res => res.json()).subscribe(
      data => console.log('success'), 
      error => console.log(error)) 
    } 
} 

缺少什麼我在這裏?

回答

0

我終於找到了解決方案。 該Content-Type頭格式錯誤:在實際的代碼

Content-Type: , multipart/form-data; boundary=----WebKit12345 

內容類型報頭被預先設定。 通過調用

headers.set('Content-Type', ''); 

我認爲,此時的標題內容類型被覆蓋,但實際上是空字符串前面加上它,所以,有一個逗號,它不能被解析的,當然。

headers.delete('Content-Type'); 

我通過完全刪除內容類型報頭解決了這個