【发布时间】:2020-01-17 00:23:12
【问题描述】:
在我的项目中,我在后端有 Spring Boot,在前端有 React.js。
我知道我的后端工作正常,因为我已经用 Postman 对其进行了测试。
在上传文件的前端,我有一个名为SubmitAssignment,看起来像这样:
state={file:''};
uploadFile = (e) =>{
e.preventDefault();
var formData = new FormData();
formData.append("file", this.state.file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
if(xhr.status === 200) {
console.log("upload successful");
} else {
console.log("upload failed");
}
};
xhr.send(formData);
};
onInputChange = (e) =>{
this.state.file=e.target.value;
console.log(this.state.file);
};
render() {
return (
<div>
<h1>Please select file(s):</h1>
<form>
<input className="input-file" id="my-file" type="file" onChange={this.onInputChange}/>
<button onClick={this.uploadFile}>Upload</button>
</form>
</div>
);
}
但问题是每次上传都失败。也许原因是路径,不确定。我试图console.log 路径。我得到的是 C:\fakepath\Screenshot (187).png
现在我的问题是,如果是因为路径,我该如何正确地做到这一点(据我所知,浏览器出于安全考虑不允许这样做)?
否则,有什么问题?如何解决?
浏览器控制台报错:
POST http://localhost:8080/uploadFile 400
还有,
{"timestamp":"2019-09-16T07:20:30.382+0000","status":400,"error":"Bad Request","message":"Required request part 'file ' 不存在","trace":"org.springframework.web.multipart.support.MissingServletRequestPartException: 所需的请求部分 'file' 不存在\r\n\tat .......
Here 是完整的错误消息。
如果出于任何原因需要 REST:
@PostMapping("/uploadFile")
public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
return new UploadFileResponse(fileName, fileDownloadUri,
file.getContentType(), file.getSize());
}
【问题讨论】:
标签: reactjs spring spring-boot post xmlhttprequest