A
I am answering my question, because in the future someone may have the same doubt, or want to know how to upload files with Ajax and Java1 - Add the Html<form id="form" action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="imagem" id="file"/>
<input type="submit" value="Enviar" />
<span id="msg"> </span>
</form>
2 - JsWith Jquery$("#form").on("submit", function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "upload",
method: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function (json) {
// Aqui você receberia do json um status talvez, que diz se foi feito o upload com sucesso ou não. No nosso caso vamos simular que sim.
$("#msg").text("foi");
}
});
});
It's important. note that, we cannot capture the image to send with the ajax request with $("#file").val() this would return only a symbolic path of the image, you can test using console.log($("#file").val()). To really receive the image I used the Object form, receiving as a parameter our Form, it does all part of taking the image itself and leaving the way to be sent to the server (I believe there are other ways to actually receive the image).All right, let's go back end3 - Java OBS: place the annotation @MultipartConfig() in your servlet.. I will put parts of the code and explain// pegando a imagem
Part imagem = request.getPart("imagem");
Here we are simply creating a Part object, using the request.getPart(), in the method parameter, place the attribute name name that used in the tag input type="file" //verificando se a pasta onde o upload será salvo existe, se não existir vamos criar
File pasta = new File("C:"+File.separator+"upload");
if(!pasta.exists()){
//não existe, bora criar
pasta.mkdir();
}
No we are using getRealPath to create the folder path we will use to save the images for reasons that can be read https://stackoverflow.com/questions/18664579/recommended-way-to-save-uploaded-files-in-a-servlet-application/18664715#18664715 , I advise you also do not use getRealPath.All right, if the folder exists... else {
// criando referencia do arquivo
File img = new File("C:" + File.separator + "upload" + File.separator + "teste.jpg");
// criando arquivo em si
img.createNewFile();
}
When we create a File new File(caminho e nome do file), in fact, the File class only creates an empty link, "assuming" that the File already exists, but this does not create any file, to actually create the file, we use the method createNewFile(), this creates an empty file. (if you debug the code, and stop after the line of img.createNewFile() you can see this, a file created but empty).All right. created folder, created file, now we will simply save the image inside the file! // gravando imagem no arquivo
imagem.write("C:" + File.separator + "upload"+ File.separator+"teste.jpg");
Okay, when executed, the method writer writes the data Part inside the file, that is, it records the image inside the file, if you check and everything is correct, the file should be in the directory C:/upload/ with the image recorded on it.Note:the method writer You can fire an Exception if the file doesn't exist.If the file already exists (in our case, teste.jpg) the writer will overwrite the old data, with the new ones, that is, will replace the current image, for which it has just been sent Good. that's it personal, it's a simple way to upload images with java, I hope this helps