POST 一个包含 React.js 的文件

POST a file with React.js

最终用户应该通过文件浏览器上传 excel 文件:

<FloatingActionButton title="Upload excel" primary className="import-vendor"
                      containerElement="label"
                      label="Browse file">
      <input onChange={(e) => Actions.uploadXLS(e.target.files[0])} 
             type="file" 
             name="xls" 
             accept="application/vnd.ms-excel" 
             style={{ display: 'none' }}/>
      <UploadIcon/>
</FloatingActionButton>

操作:

uploadXLS(file) {
    this.getInstance().callUploadXLS( file );
}

服务:

callUploadXLS: {
    remote( state, data ) {
        const url = `${base}/vendor/form`;
        return $http.instance.api.post( url, data );
    },
    success: Actions.XLSUploaded,
    error: Actions.fail
}

此文件应发送到 POST REST 端点,该端点使用 Spring 引导构建,接受多部分文件。端点无法识别像这样发送文件

error: "Internal Server Error"
exception :"org.springframework.web.multipart.MultipartException"
message : "Current request is not a multipart request"
path : "/vendor/form"
status : 500
timestamp : 1501747384079

如何 post excel 文件?

编辑:我正在尝试 post 文件列表:

const arrayOfFile = [];
let i = 0;
for ( i = 0; i < files.length; i++ ) {
  const data = new FormData();
  arrayOfFile[i] = data.append( 'file', files[i] );
}
this.getInstance().callUploadXLS( arrayOfFile );

但 data.append( 'file', 文件[i] );总是 returnin undifined

尝试使用 good file uploader and inspect element check your network tab whether you api call that is file upload is sending proper file data as expected by the server. Test the API from Postman 如果它工作那么它意味着 front-end 代码有问题,你可以比较 headers 你发送的错误项目。

希望这个调试方法能帮助你认清错误。

将文件传递到后端是通过 multipart/form-data 表单完成的。

如果您检查您现在发送到后端的请求,您会发现您的请求没有发送(可能)multipart/form-data

您可以查看参考What does enctype='multipart/form-data' mean?问题。

您的代码应该类似于:

callUploadXLS: {
    remote( state, file ) {
                // ^ make sure that `file` here is the same target.files[0]. It should be `File` Object

      // Will turn your form to `multipart/form-data`
      var data = new FormData();
      data.append('file', file);

      const url = `${base}/vendor/form`;
      return $http.instance.api.post( url, data );

    },
    success: Actions.XLSUploaded,
    error: Actions.fail
}