Upload with ajax and java

0

I'm doing an image upload with ajax (I already tested it 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 file in java:

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

I get the error:

  

the request does not contain a multipart / multipart / multipart / form   stream, content type header is application / x-www-form-urlencoded;   charset = UTF-8

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

    
asked by anonymous 05.07.2017 / 20:06

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 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

06.07.2017 / 05:41
0

try putting this attribute:

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

or

processData: false,
contentType: false
    
05.07.2017 / 20:59
0

To receive in the servlet you should do so:

Part arquivo= request.getPart("nome_arquivo");
InputStream sInputStream = arquivo.getInputStream();
    
05.07.2017 / 21:07