1

I want to send an uploaded image file along with data entered by the user to the backend which is implemented on JAVA.

`const payload = {
        id: null,
        name : Name,
        email : Email

        };
        //data.append("myjsonkey", );

        await fetch('http://localhost:8080/student/insertStudent', {
            method: 'POST',
            body: JSON.stringify(payload),
            headers : {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
            }
        })`

Using this implementation I was able to send data to backend using POST request. I now want to attach an image file in the payload to be recieved at the backend. The Code written for the image uploading is

`fileChangedHandler = (event) => {
    this.setState({selectedFile: event.target.files[0]})
    }

    uploadHandler = () => { 
    console.log(this.state.selectedFile)
    }
render() {
        return (
            <div>
                <input type="file" onChange={this.fileChangedHandler}/>
                <button onClick={this.uploadHandler}>Upload!</button>
            </div>
        );
    }`

Any help will be highly appreciated.

5
  • This isn't java. Commented Oct 27, 2018 at 13:14
  • This is javascript. I want to send data from react.js to java backend as I mentioned clearly Commented Oct 27, 2018 at 13:20
  • You aren't showing us the backend code so there is no need to tag java. Commented Oct 27, 2018 at 13:22
  • Oh, I am so sorry. Commented Oct 27, 2018 at 14:00
  • To send an uploaded file from html form using javascript to java backend, you need to use multipart in the form tag, I have just said that in case if you sending data from a form. though you have not mentioned about form though. Commented Oct 27, 2018 at 15:05

1 Answer 1

3

You can send data using formData... here is the sample code for api request in react.

uploadHandler = () => { 
   const formData = new FormData();
   formData.append('file', this.state.selectedFile);
   axios.post('http://localhost:8080/student/image',
   formData
);
}

Java controller

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/student/")
public class StudentController {

@RequestMapping(value = "image" ,method = RequestMethod.POST, consumes = "multipart/form-data")
    @ResponseStatus(HttpStatus.CREATED)
    public void image(
            @RequestParam("file") MultipartFile file ){
            // CODE HERE

    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.