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 point out 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 formData, that taking our Form as a parameter, it does all the part of taking the image itself and leaving it in the way to be sent to the server (I believe there are other ways to really receive the image).
All right, let’s go to the back end
3 - Java
NOTE: put the note @MultipartConfig()
in your Rvlet..
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, put the attribute name name
you used to 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();
}
Not we’re using getRealPath
to create the folder path we will use to save the images for reasons that can be read in this post, I advise you not to use the 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 File already exists, but this does not create any files, 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 the img.createNewFile()
you can see this, a file created, but empty).
Alright 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 method writer
writes the data of 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 engraved on it.
Note:
- the method
writer
can fire an Exception if the file does not exist.
If the file already exists (in our case, teste.jpg
) Writer will overwrite the old data with the new ones, i.e., replace the current image with the one just sent
Good.. That’s it guys, this is a simple way to upload images with java, hopefully this will help
I tried and it didn’t work..
– RickPariz
Man has a very nice example. https://www.codeproject.com/Articles/1020950/A-Simple-Method-to-Upload-Files-by-jQuery-Ajax-Cal
– Romario Pires