9

我正在尝试在我的代码中使用 react-dropzone 并使用 axios 向服务器发出 POST 请求,但是 POST 请求总是失败并且我不断收到以下错误:

未捕获(承诺中)错误:请求失败,状态码为 500

这是我的组件

constructor(props) {
  super(props);
  this.state = {
    accepted: [],
  };

  ['handleChange', 'handleValidSubmit'].forEach(v => {
    this[v] = this[v].bind(this);
  });
}

handleValidSubmit(event, values) {
  const data = {
    accepted: this.state.accepted,
  };
  console.log(data);
  axios({
    method: 'post',
    url:
      'https://oc6tq8iop5.execute-api.ap-southeast-1.amazonaws.com/dev/upload',
    data: JSON.stringify(data),
  }).then(data => {
    console.log(data);
    onDrop: accepted => {
      accepted.forEach(file => {
        req.attach(file.name, file);
      });
      req.end(callback);
      var formData = new FormData();
      formData.append('gambar', values.accepted);
      console.log(formData);
    };
  });
}

handleChange(event) {
  const { target } = event;
  const value = target.type === 'checkbox' ? target.checked : target.value;
  const { name } = target;

  this.setState({
    [name]: value,
  });
}

这是我的渲染方法

<div className="dropzone">
  <Dropzone
    accept="image/jpeg, image/png, image/jpg"
    onDrop={accepted => {
      this.setState({ accepted });
    }}
    maxSize={200000}
    multiple={false}
  >
    <p>Maksimal 2 MB (JPG/PNG)</p>
  </Dropzone>
  {this.state.accepted.map(f => (
    <span key={f.name}>
      {f.name} - {f.size} bytes
    </span>
  ))}
</div>
4

1 回答 1

4

您只需要使用 axios 发送标头,

const config = { headers: { 'Content-Type': 'multipart/form-data' } };
let fd = new FormData();

values.map((file) => {
  fd.append('File[]',file);
});

axios.post(`${ROOT_URL}/ImageUpload`, fd, config)
  .then((response) => {
    callback(response);
  })
  .catch(error => {
      errorResponse(error);
  })
于 2018-05-17T10:41:53.153 回答