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 Java
1 - Add 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 - Js
With 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 is important emphasize that we can not take a picture to send with ajax request with $("#file").val()
% would return it only a symbolic path of the image, you can test using console.log($("#file").val())
. To actually receive the image I used the object FormData , which received as parameter our form, it does everywhere to pick up the image itself and leave the way to send pro server (I believe there are other ways to actually receive the image).
All right, let's go to the back end
3 - Java
NOTE: put the @MultipartConfig()
annotation in your servlet.
I'll put parts of the code and explain
// pegando a imagem
Part imagem = request.getPart("imagem");
Here we are simply creating a Part object, using request.getPart()
, in the method parameter, put the name of the name
attribute that used in the input type="file"
tag
//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 are using getRealPath
to create the folder path to use it to save images for reasons that can be read in this post , I advise you not to use%
Very well, 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 you create a File getRealPath
actually the File class only creates an empty link, "assuming" that the File already exists, but it does not create any files, to actually create the file, use the new File(caminho e nome do file)
method %, this creates an empty file. (if you debug the code, and stop after the createNewFile()
line you can see this, a created but empty file).
Well done guys .. created folder, created file, now let's simply save the image inside the file!
// gravando imagem no arquivo
imagem.write("C:" + File.separator + "upload"+ File.separator+"teste.jpg");
Ready, when executed, the img.createNewFile()
method writes the writer
data inside the file, that is, it writes the image inside the file, if you verify and everything is correct, the file should be in the directory Part
with the image recorded on it.
Note:
- method
C:/upload/
can trigger an Exception if the file does not exist.
-
If the file already exists (in our case, writer
) the writer will overwrite the old data with the new ones, that is, it will replace the current image,
Well .. this is personal, this is a simple way to upload images with java, hope this helps