2017-11-06 10 views
1

다음은 파일 업로드를위한 코드입니다.reactjs에서 업로드 한 파일이 작동하지 않습니다. 작동하지 않는 reactjs에서 파일 업로드에 대한 POST 호출

<form encType="multipart/form-data" action=""> 
    <input type="file" name="fileName" defaultValue="fileName"></input> 
    <input type="button" value="upload" onClick={this.handleClick.bind(this)}></input> 
</form> 


handleClick(){ 
      let deliveryId = this.props.params.deliveryId; 
      var data = new FormData(); 
      var imagedata = document.querySelector('input[type="file"]').files[0]; 
      data.append("data", imagedata); 
      console.log('Data', data); 

      fetch(apiBaseUrl, { 
       mode: 'no-cors', 
       method: "POST", 
       body: JSON.stringify({ 
        'item_file': data, 
        'delivery_id': deliveryId, 
        'description': 'test description' 
       }) 
      }).then(function (res) { 
       if (res.ok) { 
        alert("Perfect! "); 
       } else if (res.status == 401) { 
        alert("Oops! "); 
       } 
      }, function (e) { 
       alert("Error submitting form!"); 
      }); 
     } 

'imagedata'에서 파일 세부 사항을 볼 수 있지만 '데이터'가 비어 있습니다. 왜 '데이터'가 비어 있는지 파악할 수 없습니다. 그렇기 때문에 백엔드 호출이 실패하는 것입니다.

는 다음 후 제출 서버로가는 요청 페이로드 :

{item_file : {}, delivery_id "eeb9422e-9805-48eb-a8be-ad2e27f3f643"설명 : "테스트 설명"}

답변

2

FormData 자체를 사용하여 deliveryId과 같은 추가 매개 변수를 사용하여 파일을 업로드 할 수 있습니다. 그리고 파일을 문자열로 지정할 수 없습니다.

handleClick() { 
    let deliveryId = this.props.params.deliveryId; 
    var imagedata = document.querySelector('input[type="file"]').files[0]; 

    var data = new FormData(); 
    data.append("item_file", imagedata); 
    data.append('delivery_id', deliveryId); 
    data.append('description', 'test description'); 

    fetch(apiBaseUrl, { 
     mode: 'no-cors', 
     method: "POST", 
     body: data 
    }).then(function (res) { 
     if (res.ok) { 
      alert("Perfect! "); 
     } else if (res.status == 401) { 
      alert("Oops! "); 
     } 
    }, function (e) { 
     alert("Error submitting form!"); 
    }); 
}