0

I am trying (unsuccessfully so far) to attach a file (an image) to my JSON data to call a method in my webservice.

I found some posts regarding the sending of just an image but not an image as part of a json data object.

The call works if i leave "imageFile" as 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 the web service side i am calling this method:

 @Path("/add")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public void addUser(Picture picture){

        userService.persistPicture(picture);

    }

with this constructor for the 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 you can point me in the right direction!

Thx in advance!

Seren
  • 131
  • 1
  • 5

1 Answers1

0

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 you receive base64 encoded value which you can convert to binary easily.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • i am sorry but while i understand that filereader does help me, i dont understand your code snippet and how i have to use the filereader in my case. – Seren May 08 '15 at 12:31
  • @Seren - code is reading file from input type element of type file , so when ever change in file it read using filereader ..if you already have file than you just direcly give file name to file reader ...than ajax method call for the file array but if you dont have multiple file than remove each part of the code..i hope it helps you to understand – Pranay Rana May 08 '15 at 12:34