【问题标题】:POST a file with React.js使用 React.js 发布文件
【发布时间】:2023-03-21 04:07:02
【问题描述】:

最终用户应该通过文件浏览器上传一个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
}

这个文件应该被发送到一个使用 Spring boot 构建的 POST REST 端点,该端点接受一个多部分文件。端点无法识别像这样发送文件

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

如何发布excel文件?

编辑:我现在正在尝试发布文件列表:

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', files[i]);总是返回未定义的

【问题讨论】:

  • 你能不能也在这里添加动作代码Actions.uploadXLS
  • @dinchev 检查更新
  • const data = new FormData(); 移动到您的 for 循环之前。并为 ajax 调用提供data,而不是arrayOfFile
  • 我这样做了,但结果相同。
  • 让 i = 0;常量数据 = 新 FormData(); for ( i = 0; i

标签: reactjs post spring-boot reactjs-flux


【解决方案1】:

尝试使用good file uploader 并检查元素检查您的网络选项卡是否您的 api 调用即文件上传正在发送服务器预期的正确文件数据。从Postman 测试 API,如果它正常工作,则意味着前端代码有问题,您可以比较标头您发送的错误项目。

希望这种调试方法能帮助您识别错误。

【讨论】:

  • 错误:“内部服务器错误”异常:“org.springframework.web.multipart.MultipartException”消息:“当前请求不是多部分请求”路径:“/vendor/form”状态:500时间戳:1501747384079
【解决方案2】:

通过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
}

【讨论】:

  • 如果我想上传文件列表怎么办?请检查更新,感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2017-12-26
  • 2018-08-26
  • 2022-12-18
  • 2020-07-01
  • 2016-08-29
  • 1970-01-01
  • 2014-04-10
  • 2015-04-03
相关资源
最近更新 更多