![](/img/trans.png)
[英]React-app frontend & express backend using nginx on ubuntu
[英]Upload file using React frontend app and Spring (Java) backend app
我有一个项目使用Java的Spring作为后端,使用React作为前端,我想将文件上传到服务器。 在后端,我有一个具有以下方法的Spring控制器:
@RequestMapping("/upload-file")
public void uploadFile (MultipartHttpServletRequest multipartHttpServletRequest) {
//save on server logic comes here
}
在前端,我想使用一些npm库上载文件。 问题是我发现的所有库都不以Spring控制器可以处理的方式发送文件。 也许我缺少了一些东西:从React前端上传文件到Spring后端的最佳方法是什么?
我已经使用react-dropzone上传文件,不确定它是否与Spring兼容。 你可以试试看。
一个例子,如何使用它
<div className='dropzone'>
<Dropzone
name={name}
multiple={false}
onDrop={(filesToUpload, e) => {
return input.onChange(filesToUpload)
}}>
</Dropzone>
</div>
前端:如果您使用的是前面提供的react-dropzone ,则可以使用以下代码发送带有文件的请求:
onDrop(accepted, rejected) {
if (rejected.length) {
//do something with rejected files
} else {
let data = new FormData();
for (let i = 0; i < this.state.files.length; i++) {
let file = accepted[i];
data.append("file" + i, file, file.name);
}
const config = {
headers: { 'content-type': 'multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p' }
};
axios.post("upload-files", data, config);
}
};
后端:
@RequestMapping(value = "/upload-files", headers = "content-type=multipart/*", method = RequestMethod.POST)
public void upload(@RequestParam(value = "file0", required = true) MultipartFile multipartFile, Integer adminOid) throws IOException {
//do something with the multipartFile
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.