0

I am posting a form of type file and I am handling that POST request in spring-boot controller by returning JSON data. I checked that request with postman its working fine, But when I am using onreadystatechange method in react it is giving xhr status =0

onSubmitForm(){
    console.log("entered");
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/images', true);
    //xhr.responseType = 'text';

    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');

    var data = new FormData();
    var imageFile = document.querySelector('input[type="file"]').files[0];
    console.log( imageFile);

    data.append("imageFile", imageFile);


    xhr.onreadystatechange = function () {
        if(xhr.readyState === XMLHttpRequest.DONE ){
            alert(xhr.status);
            if(xhr.status === 200){
                alert('hi there');
                }
        }
    }
    xhr.send( data );

}

render() {
    return (
        <div>
            <form encType="multipart/form-data" action="">
                File to upload:
                    <input type="file" name="imageFile" accept="image/*" />
                    <input type="submit"  value="Upload" onClick={  this.onSubmitForm.bind(this) } />
            </form>
        </div>
    )
}

I am receiving the correct data in controller, But I am not getting JSON from POST request ??

controller

@PostMapping("/images")
public  @ResponseBody JSONModel addContent( @RequestParam("imageFile") MultipartFile file,  
        imageApp content ) {

    String encodedfile = null ;
    double fileSize = file.getSize();

    try {
            byte[] bytes=file.getBytes();
            System.out.println(fileSize/(1024*1024));
            encodedfile = Base64.getMimeEncoder().encodeToString(bytes);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    content.setDate(LocalDateTime.now());

    content.setLocation(UUID.randomUUID().toString() );
    content.setId(UUID.randomUUID().toString() );
    content.setContent(encodedfile);
    return service.addContent(content);
    }

service

public @ResponseBody JSONModel addContent(imageApp content) {
    return new JSONModel(1, respository.save(content).getLocation());
}
harish chava
  • 252
  • 2
  • 19

1 Answers1

0

Make <input type="submit" to type="button", keeping type="submit" tells the browser that page/form has to be submitted and it causing conflicting behavior which we need to prevent. So either change the type="button" or you can prevent the default behavior by taking the event in your handler and calling e.preventDefault();

Amit K Bist
  • 6,760
  • 1
  • 11
  • 26