0

In my project, I have Spring Boot in the back-end and React.js in the front.

My back-end is working fine, I know, because I have tested it with Postman.

In the front-end to upload file, I have a named SubmitAssignment, which looks like this:

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>
    );
}

But the problem is upload is failing every time. Maybe the reason is the path, not sure. I tried to console.log the path. And what I got is C:\fakepath\Screenshot (187).png

Now my question if it is because of path, how can I do it correctly(as far as I know browser doesn't allow it for security concern)?

Otherwise, what is the problem? How to solve it ?

The error in browser console :

POST http://localhost:8080/uploadFile 400

And,

{"timestamp":"2019-09-16T07:20:30.382+0000","status":400,"error":"Bad Request","message":"Required request part 'file' is not present","trace":"org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present\r\n\tat .......

Here is the full error message.

If the REST is needed, for any reason :

@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 Answer 1

1

From what I could see, in onInputChange() you are assigning the target value this.state.file=e.target.value; (This has the file path not the actual file)

Instead change to below, Important !

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

And some suggestions are, use Fetch Api to send post request rather than using Plain old 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));

In your Spring boot controller use @RequestPart("file")

@PostMapping("/uploadFile")
public UploadFileResponse uploadFile(@RequestPart("file") MultipartFile file) {
//Logic
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain why use @RequestPart("file") instead of @RequestParam("file")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.