Upload with ajax and java

Asked

Viewed 1,010 times

0

I am doing an image upload with ajax (already tested without ajax and it worked).

JS:

$("#upload").on("submit", function(e) {
    e.preventDefault();
    $.ajax({
      url: $("#controller").val(),
      type: "POST",
      data: $(this).serialize(),
      enctype: 'multipart/form-data',
      success: function(json) {
        if (json.status) {
          iziToast.success({
            title: 'Ok',
            message: json.message,
            icon: "fa fa-check",
            timeout: 2500,
            position: "center",
          });
        } else {
          iziToast.error({
            title: 'Erro',
            message: json.message,
            icon: "fa fa-times"
          });
        }
      },
      error: function() {
        iziToast.error({
          title: 'Erro',
          message: "Erro ao fazer requisição",
          icon: "fa fa-times"
        });
      }
    });
  });

The problem is that when I get to the receiving part of the java file:

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

get the bug:

the request doesn’t contain a Multipart/form-data or Multipart/Mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8

I’ve already put the enctype: 'multipart/form-data' in the ajax request, but still the periste error.

3 answers

1


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

0

try putting this attribute:

contentType: "multipart/form-data; charset=utf-8"

or

processData: false,
contentType: false
  • I tried and it didn’t work..

  • Man has a very nice example. https://www.codeproject.com/Articles/1020950/A-Simple-Method-to-Upload-Files-by-jQuery-Ajax-Cal

0

To receive in Servlet you must do so:

Part arquivo= request.getPart("nome_arquivo");
InputStream sInputStream = arquivo.getInputStream();
  • I am using Commons-Fileupload

  • @Rickpariz if you want to take a look, I have a public git project uploaded. https://gitlab.com/Jeffersonvh/spolifly/

  • you use ajax ?

  • @Rickpariz No, but if the problem is time to receive it is worth taking a look

  • what is the name of the class responsible for the upload ? I am looking there but can’t find anything

  • @RickPariz https://gitlab.com/Jeffersonvh/spolifly/blob/master/src/java/servlet/CadastraMusica.java

  • Thank you, I’ll take a look

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.