I'm creating an application and need a way to upload xls / xlsx files, sending the front-end (Ajax) file to the backend (Java) so it can be manipulated.
Ajax code:
$("#formulario").submit(function () {
var formData = new FormData(this);
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (data, status, jqxhr) {
alert('sucesso');
},
error: function(){
alert('deu erro');
},
cache: false,
contentType: false,
processData: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', function () {
alert('upando o arquivo');
}, false);
}
return myXhr;
}
});
});
The Ajax code is working perfectly, it executes and returns the code 200. However, I can not 'receive' the file in Java.
Java code:
@POST
@Path("/upload")
@Consumes("multipart/form-data")
public Response create(@MultipartForm FileUploadForm input){
System.out.println("funcionou");
//manipulo o arquivo
return Response.ok;
}
I hope you can help me and guide me to make it work.
UPDATE
I made a change in ajax, and finally I was able to get JAVA to receive the request
$(document).ready(function () {
$(function () {
var form;
$('#fileUpload').change(function (event) {
form = new FormData();
form.append('fileUpload', event.target.files[0]); // para apenas 1 arquivo
//var name = event.target.files[0].content.name; // para capturar o nome do arquivo com sua extenção
});
$('#btnEnviar').click(function () {
$.ajax({
url: 'http://localhost:8080/SferaCR/rest/importacao', // Url do lado server que vai receber o arquivo
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert('sucesso');
$('#fileUpload').val('');
},
error: function (){
alert('deu erro');
$('#fileUpload').val('');
}
});
});
});
});
However, the problem now is that in java, you are getting the 'input' parameter as null. That is, the request goes, 'right', but the file is not sent.