2017-06-01 4 views
2

私は反応が新しく、ノードのバックエンドにファイルをアップロードしようとしていますが、これをしばらくしても動作しません。私は正しく私のハンドル関数にデータを送信するようだが、その後私は私のformDataオブジェクトに追加することはできません。ファイルアップロード時に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); 
     }); 

私がコンソールとデータファイルのデータオブジェクトをログアウトすると、次の結果が得られます。

this is the value of data in uploadAction FormData {} 

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

だから何とか私のFILEDATAが正しく持ち込まれているように見えますが、これは、データオブジェクトに添付されている方法についての切断があります。私は混乱しています。これは、これらのものをオンラインで見ることから、このデータオブジェクトを追加する方法であるようです。私のアクシオスコールは正しいと思うが、私はもちろんその前にエラーになっている。

私はこれをどのように修正することができるでしょうか? querySelectorの使用を伴わない反応でこれを行う簡単な方法はありますか?私はおそらくdropzoneまたは同様のライブラリ/パッケージを使用したくない、私はちょうど簡単なアップロードファイルを行う方法を学びたい。

誰かがこれに関する提案をいただければ、本当に感謝します。私はこれにいくつかの時間を費やして、私はサークルに入っているようです。

編集:I下記の最初のコメントの提案ごとに試してみて、自分のデータ値(すなわち、データフォームオブジェクト)をログコンソールに自分のコードに

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

を追加しました。結果は次のとおりです。

file, [object File] 

これは間違いありませんが、私の問題の解決には役立ちません。

+0

可能な複製(https://stackoverflow.com/questions/17066875/how-to-inspect-formdata)私はその解決策を試してみた –

+0

私が必要としていたように機能しませんでした。私は私のコメントを編集します。 –

答えて

0
(データはあなたのいるFormDataである)、次のようにあなたの呼び出しを変更し

し、それが動作するはずです:

​​

それに加えて、あなたが反応を使用しているとして、代わりにquerySelectorを使用しての、あなたがのonChangeを使用することができますイベントを入力します。ただ、一例として :[?いるFormDataを検査する方法]の

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> 
     ) 
    } 
    } 
関連する問題