首页 > 解决方案 > 使用 react + Vertx 上传文件

问题描述

我正在开发一个 Web 应用程序,我必须将一个用 Java + VertX 编写的文件上传到服务器

端点是这样制作的:

private void uploadFromExcel(RoutingContext ctx) {    
    new ImportFromExcel(ctx.getBody(), ctx.vertx()).startImporting(ev->{
        if(ev.failed()){
            ctx.fail(ev.cause());
        }else {
            ctx.response().end();
        }
    });        
}

前端是这样的:

<input
   accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
   type="file"
   onChange={this.onUploadFile}
 />
   <label htmlFor="flat-button-file">
     <IconButton component="span">
         <Icon className={'material icons'}>cloud_upload</Icon>
     </IconButton>
   </label>

[...]

onUploadFile = (e) =>{
   const {reduxApi, setError, setWait, removeWait} = this.context
   const { dispatchUploadFile } = this.props

   const fileToUpload = e.target.files[0]

   dispatchUploadFile(reduxApi, fileToUpload , (err,data)=>{
      removeWait()
      //e.target.value = null
      if(err){
        setError(err)
        return
       }
   })

   [...]

   dispatchUploadFile: (reduxApi, file, cb) =>{
      dispatch(reduxApi.actions.cryptoindexUploadExcel.post(null,file,cb))
   }

我可以使用标题“Accept-Type”:“multipart/form-data”通过邮递员上传文件。它工作正常!

不幸的是,我无法通过反应上传文件,它会引发错误。所以我决定尝试另一种解决方案

let  reader = new FileReader()
reader.onload = (event)  => {
    let arrayBuffer = event.target.result
    let array = new Uint8Array(arrayBuffer)
    let binaryString = String.fromCharCode.apply(null, array)
    console.log(binaryString)

    setWait()
    dispatchUploadFile(reduxApi, array , (err,data)=>{
      removeWait()
      if(err){
        setError(err)
        return
      }
    })

}
reader.readAsArrayBuffer(fileToUpload)

这段代码读取文件,但后端部分显示“零字节长文件”。你有什么解决办法?谢谢!

标签: reactjsfile-uploadreact-reduxvert.x

解决方案


我假设在服务器端你BodyHandler的路由器中有:

router.route().handler(BodyHandler.create());

现在,根据您上传文件的方式,它可能会出现在 2 个地方:

如果它是 a multipart/form-data,它将在fileUploads()getter 下的上下文中可用:

Set<FileUpload> uploads = routingContext.fileUploads();
// Do something with uploads....

它是一个正文上传,例如像 AJAX 这样的调用application/json它最终在body()getter 中。因此,请确保您使用正确的标头,因为在上传期间浏览器和服务器对它们的处理方式不同。


推荐阅读