react.js文件未上传Spring服务器

时间:2019-09-16 07:29:51

标签: reactjs spring spring-boot post xmlhttprequest

在我的项目中,后端有 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 “不存在”,“跟踪”:“ org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分“文件”不存在\ 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());
}

1 个答案:

答案 0 :(得分:1)

据我所见,在onInputChange()中,您正在分配目标值this.state.file=e.target.value;(该文件路径不是实际文件)

改为下面的重要!

  

this.state.file=e.target.files[0];

有些建议是,使用Fetch Api发送帖子请求,而不要使用普通的旧Javascript

const formData = new FormData();
formData.append("file", this.state.file);
fetch('http://localhost:8080/uploadFile', {
    method: 'POST',
    body: formData
  })
   .then(success => console.log(success))
   .catch(error => console.log(error));

在您的Spring启动控制器中,使用@RequestPart("file")

@PostMapping("/uploadFile")
public UploadFileResponse uploadFile(@RequestPart("file") MultipartFile file) {
//Logic
}