2017-06-01 38 views
2

我是新的反應,我試圖上傳一個文件到我的節點後端,但我已經花了一段時間在這個,不能讓它工作。我似乎將數據正確地發送到我的句柄函數,但在此之後,我不能將它附加到我的formData對象。無法追加到表單數據對象在文件上傳在反應

這裏是我從我的上傳html調用一個句柄提交按鈕的功能。

uploadAction(){ 
    var self = this; 
    console.log('inside uploadAction'); 

    var data = new FormData(); 
    // var filedata = {}; 
    var filedata = document.querySelector('input[type="file"]').files[0]; 

    data.append('file', filedata); 

    console.log('this is the value of data in uploadAction ', data); 
    console.log('this is the value of filedata in uploadAction ', filedata) 

    const config = { headers: { 'Content-Type': 'multipart/form-data' } }; 
    axios.post('http://localhost:5000/upload',{ 
     filedata: data 
    },config) 
     .then((response)=>{ 
     console.log('back again success from upload'); 
     }) 
     .catch((err)=>{ 
     console.error('error from upload ', err); 
     }); 

所以當我控制檯註銷數據和filedata對象時,我得到以下結果。

this is the value of data in uploadAction FormData {} 

this is the value of filedata in uploadAction File {name: "suck.jpg".... 

所以在某種程度上,似乎我的FILEDATA被帶到正確的,但有這個如何被附加到數據對象的脫節。我感到困惑,因爲這似乎是我發現通過在線查看這些東西來追加這個數據對象的方式。我認爲我的axios電話是正確的,但我當然在這之前遇到了一個錯誤。

有沒有人有任何建議我如何解決這個問題?有沒有更簡單的方法來做到這一點在反應,不涉及使用querySelector?我可能不想使用dropzone或類似的庫/包,我只想學習如何做一個簡單的上傳文件。

如果有人對此有任何建議,我會非常感激。我花了一些時間在這方面,我似乎在圈子裏。

編輯:按照第一個評論的建議,下面我加入

for (var pair of data.entries()) { 
    console.log(pair[0]+ ', ' + pair[1]); 
} 

我的代碼,試圖控制檯登錄我的數據值(即數據形的對象)。結果是:

file, [object File] 

雖然這是真的,但它並沒有幫助解決我的問題。

+0

的可能的複製[如何檢查FORMDATA?](https://stackoverflow.com/questions/17066875/how-to-inspect-formdata) –

+0

我已經試過了解決方案,並沒有按我的需要工作。我將編輯我的評論。 –

回答

0

您的通話更改爲以下方式,它應該工作(數據是你的FORMDATA):

​​

除了它,因爲你正在使用的不是使用querySelector反應,你可以使用的onChange來自您的文件輸入的事件。 只是作爲一個例子:

import React,{Component} from 'react' 
    class UploadComponent extends Component { 
     constructor(props, context) { 
     super(props, context); 
     this.state = {file: null}; 

     this.handleFileChange = this.handleFileChange.bind(this); 
     this.sendFile = this.sendFile.bind(this); 
     } 

     handleFileChange(event) { 
      this.setState({file:event.target.files[0]}) 
     } 

     sendFile() { 
      //In here you can get the file using this.state.file and send 
     } 

     render() { 
     return(
      <div> 
       <input className="fileInput" type="file" onChange={this.handleFileChange}/> 
       <button type="submit" onClick={this.sendFile}>Upload </button> 

      </div> 
     ) 
    } 
    }