java - Attach Image to ajax POST request data for web service call -


i trying (unsuccessfully far) attach file (an image) json data call method in webservice.

i found posts regarding sending of image not image part of json data object.

the call works if leave "imagefile" null.

$("#butsubmit").click(function(){	  		  		var files = document.getelementbyid('files').files;  		var file = files[0];  	          $.ajax({  		type: "post",  		contenttype: "application/json; charset=utf-8",  		datatype: "json",  		url:"http://localhost:8080/sampleapp/api/users/add",  		data: json.stringify({"description":"test2","title":"testest2","uploadername":"seren","imagefile":file})    		  		  });		  	});

on web service side calling method:

 @path("/add")      @post      @produces(mediatype.application_json)      @consumes(mediatype.application_json)      public void adduser(picture picture){            userservice.persistpicture(picture);        }

with constructor class picture:

 @jsoncreator     public picture(              @jsonproperty("description") string description,              @jsonproperty("title") string title,              @jsonproperty("uploadername") string uploadername,              @jsonproperty("imagefile") byte[] imagefile) {          this.uploadername = uploadername;          this.title = title;          this.description = description;          this.imagefile = (byte[]) imagefile;      }

i hope can point me in right direction!

thx in advance!

make use of filereader object available in javascript - html 5 file api (browser support)

    var files = [];      $("input[type=file]").change(function(event) {       $.each(event.target.files, function(index, file) {         var reader = new filereader();         reader.onload = function(event) {             object = {};           object.filename = file.name;           object.data = event.target.result;           files.push(object);         };           reader.readasdataurl(file);       });     });  //post file using ajax call $.each(files, function(index, file) {     $.ajax({url: "/ajax-upload",           type: 'post',           data: {filename: file.filename, data: file.data},           success: function(data, status, xhr) {}     });         }); 

on serverside receive base64 encoded value can convert binary easily.


Comments