Uploading files using REST and Java

Asked

Viewed 1,332 times

0

I am creating an application and need a way to upload xls/xlsx files by sending the file from the front end (Ajax) to the back end (Java) so it can be manipulated.

Ajax code:

$("#formulario").submit(function () {
                var formData = new FormData(this);

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: formData,
                    success: function (data, status, jqxhr) {
                        alert('sucesso');
                    },
                    error: function(){
                        alert('deu erro');
                    },
                    cache: false,
                    contentType: false,
                    processData: false,
                    xhr: function() {  
                        var myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) { 
                            myXhr.upload.addEventListener('progress', function () {

                                alert('upando o arquivo');
                            }, false);
                        }
                    return myXhr;
                    }
                });
            });

Ajax Code is working perfectly, it runs and returns me the code 200. However I cannot 'receive' the file in Java.

Java code:

@POST
@Path("/upload")
@Consumes("multipart/form-data")
public Response create(@MultipartForm FileUploadForm input){
    System.out.println("funcionou");
    //manipulo o arquivo
    return Response.ok;
}

I hope you can help me and guide me to make it work.

UPDATE

I made a change in ajax, and finally, I managed to get JAVA to receive the request

$(document).ready(function () {
            $(function () {
                var form;
                $('#fileUpload').change(function (event) {
                    form = new FormData();
                    form.append('fileUpload', event.target.files[0]); // para apenas 1 arquivo
                    //var name = event.target.files[0].content.name; // para capturar o nome do arquivo com sua extenção
                });

                $('#btnEnviar').click(function () {
                    $.ajax({
                        url: 'http://localhost:8080/SferaCR/rest/importacao', // Url do lado server que vai receber o arquivo
                        data: form,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function (data) {
                            alert('sucesso');
                            $('#fileUpload').val('');
                        },
                        error: function (){
                            alert('deu erro');
                            $('#fileUpload').val('');
                        }
                    });
                });
            });
        });

However, the problem now is that in java, which is receiving the parameter 'input' as null. That is, the request will, from 'right', but the file is not sent.

  • where the variable is coming from url in your javascript code and what it contains within it?

  • What JAX-RS implementation you’re using?

  • My suggestion is that you search the documentation of FileUploadForm that you are using. Most likely it is some library that works with Buffers... or bytearrays. In any of the options it is quite simple to convert to a file and save somewhere on your server.

  • @CIRCLE contains json (or xml), which returns the REST data.

  • @Luídne am not using any JAX-RS implementation. You recommend using it?

  • @Jorgecampos said thanks for your help. But even if this happened and I had some mistake there, would not have an Exception in java? Because nothing happens.

  • @Ericosouza what you mean is that you’re not printing the "worked". If so, that’s not what I had understood. If this is the case, what is being passed in the parameter url of the ajax function?

  • @Jorgefields is not that it is not printing did not work. The problem is that my ajax, sends upload file. But java 'does not receive'. Something like that.

  • How is your form tag in your html/jsp, the form with id 'form'?

  • @Jorgecampos follows below: &#xA;<form id="formulario" method="post" name="fileupload" enctype="multipart/form-data" method="post">&#xA; <input name="arquivo" type="file" />&#xA; <button>Enviar</button>&#xA;</form>

  • The url, I’m using a Rest (json/xml), which I used in other templates with Formularios and ok. But for uploading files, I can use the same?

  • Did you find a solution? Poste as an answer to help other people.

  • @Ericosouza found some solution?

Show 8 more comments

1 answer

1


I made a change in ajax, and finally, I managed to get JAVA to receive the request

$(document).ready(function () {
            $(function () {
                var form;
                $('#fileUpload').change(function (event) {
                    form = new FormData();
                    form.append('fileUpload', event.target.files[0]); // para apenas 1 arquivo
                    //var name = event.target.files[0].content.name; // para capturar o nome do arquivo com sua extenção
                });

                $('#btnEnviar').click(function () {
                    $.ajax({
                        url: 'http://localhost:8080/SferaCR/rest/importacao', // Url do lado server que vai receber o arquivo
                        data: form,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function (data) {
                            alert('sucesso');
                            $('#fileUpload').val('');
                        },
                        error: function (){
                            alert('deu erro');
                            $('#fileUpload').val('');
                        }
                    });
                });
            });
        });

However, to function properly it was necessary to remove the Annotation @Path, of my action that received the ajax request.

Browser other questions tagged

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