reactjs - 使用 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)
这段代码读取文件,但后端部分显示“零字节长文件”。你有什么解决办法?谢谢!
解决方案
我假设在服务器端你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 中。因此,请确保您使用正确的标头,因为在上传期间浏览器和服务器对它们的处理方式不同。
推荐阅读
- html - 响应式网格不适用于 grid-auto-flow: dense
- python - LSTM模型损失波动然后变高,准确度整体提高
- angular - 为什么 Angular 2+ 路由器路由定义是 Javascript 对象而不是 Typescript 类?
- bitmap - 如何将 BitmapImage 转换为 StorageFile?
- r - 查找不与现有范围重叠的时间的最近范围
- android - 错误:未定义对 'oboe::AudioStreamBuilder::openStream(oboe::AudioStream**)' 的引用
- jsf - jsf静态列表不会出现在数据表中
- spring-integration - 如何使用自定义错误通道和 WebFlux.inboundGateway 回复错误响应?
- javascript - 将对象键作为参数传递给函数
- node.js - 在本地机器上的 VSCode 中使用 NodeJS 运行带有层的 AWS Lambda