0

I create jersey REST server and receive file upload. This is the tutorial I follwed: https://gist.github.com/aitoroses/4f7a2b197b732a6a691d

Everything works fine when I try to test the server with Postman. I chose Body, form-data, key: file, value: my picture jpeg

What I try to do is to upload file using form html and jquery Here is my form

<form>
<input id="imgFile" type="file" accept="image/*" value="Add file">
                    <input id="buttonPostReview" class="buttonSend" type="submit" value="Submit">
</form>

and here is my jquery

var postFile = function(e) {
  e.preventDefault();
  var imgFile = $('#imgFile').val();
  var upLoalImgUrl = endPointUrl + 'webresources/photo';
  console.log(imgFile);
  console.log('uploading..');

  $.ajax({
            type: "POST",
            url: upLoalImgUrl,
            data: imgFile,
            async: false,
            cache: false,
            contentType: false,
            enctype: 'multipart/form-data',
            processData: false,
            success: function (returnData) {
              console.log(returnData);
              alert("Data Uploaded: ");
            }
        });
}

But I got error 415 - Unsupported Media Type Can you show me how to upload file using jquery? I try to do some search but I can find the way to do this

coinhndp
  • 2,281
  • 9
  • 33
  • 64

1 Answers1

-1

$(...).val() doesn't get a file from a file input, it just returns the name of the file. You need to do $("#imgFile")[0].files[0] and send the file with FormData:

var data = new FormData();
data.append('file', $("#imgFile")[0].files[0]);
$.ajax({ data: data, ... });
brandonchinn178
  • 519
  • 3
  • 20