Atul Sharma
Atul Sharma

Reputation: 51

how to put image in json as data

i am working on a code for rest api in which i am at page "imageTest" wth a image and button "onclick event" of the button will call function "foo()"

          @RequestMapping(value = "/imageUpload2/", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity profilePicTest(@RequestBody String data) {
    System.out.println("imageString length : " + data.length());
    System.out.println("imageUpload : " + data);

        return new ResponseEntity(null, HttpStatus.OK);

javascript part

    function foo() {
    alert('uploading image to imageupload2 url');           
    var profpic = document.getElementById("profpic");
    alert('uploading image1122334455')
    jQuery.ajax( {
        url: 'http://localhost:8090/EventApp/imageUpload2/',
        type: 'POST',
        data: { img: profpic },
        success: function( response ) {
            // response
            }
    } ); alert('uploading done')
    }

can anyone help me in the part were i can upload image by javascript (with encoding like base64) which restcontroller can accept that image string further convert into byte[] array and inserted into oracle db blob column and vice versa to send it back

------problem part---- image not uploading in json as string please anyone help me ...!

Upvotes: 1

Views: 5402

Answers (1)

Will Reese
Will Reese

Reputation: 2841

The value of data should just be the file object from the input.

HTML

<input type="file" id="profpic" />

JS

var file = $("#profpic")[0].files[0];

jQuery.ajax( {
  url: 'http://localhost:8090/EventApp/imageUpload2/',
  type: 'POST',
  data: file,
  success: function( response ) {
    // response
  }
});

Note: This doesn't work in many older browsers. IE10+ is fine but anything older than that will require a different method.

Upvotes: 1

Related Questions