</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/166221/how-can-i-upload-files-asynchronously" dir="ltr">How can I upload files asynchronously?</a>
<span class="question-originals-answer-count">
(34 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2017-11-28 22:07:01Z" class="relativetime">2 years ago</span>.</div>
</div>
</aside>
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
</div>
$(...).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, ... });