Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a file from JavaScript to a Java WebService

I have an HTML5 application, using Cordova, which you can upload files (images and videos) from your device. And I must send this file uploaded by the user to a Java WebService, and then upload it to a server.

I need help because I'm not able to achieve what I want. I try several solutions found in Internet but without success.

The WeService returns the next exception:

[org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null]

This is my code right now:

HTML:

<section id="uploadMedia">
    <input type="file" name="fileMedia" id="fileMedia" >
</section>

JS:

var file = $("#uploadMedia").find("#fileMedia")[0].files[0];
if (typeof file !== "undefined") {
    uploadFile(file);
}

 var uploadFile = function(file, callback) {
        // Create a new FormData object
        var formData = new FormData();
        formData.append('file', file);

            $.ajax({
                url: WEBSERVICE_URL + "uploadFile",
                beforeSend: function(xhr) {
                    if (WEBSERVICE_USER !== "") {
                        xhr.setRequestHeader("Authorization", "Basic " + btoa(WEBSERVICE_USER + ":" + WEBSERVICE_PASS));
                    }
                },
                data: formData,
                method: "POST",
                processData: false, // tell jQuery not to process the data
                contentType: false, // tell jQuery not to set contentType
                success: function(data, textStatus, jqXHR) {
                    alert(data);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("ERROR");
                },
                complete: function(jqXHR, textStatus) {
                    if (typeof callback === "function") {
                        callback();
                    }
                }
            });
    };

JAVA:

@MultipartConfig
@WebServlet(name = "uploadFile", urlPatterns = {"/uploadFile"})
public class UploadFile extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            String json = "";

            Part file = request.getPart("file");
            String filename = "xcvxcv";
            InputStream filecontent = file.getInputStream();

            json = "File " + filename + " successfully uploaded";
            out.print(json);                
        }
    }
}

I really appreciate every kind of help.

like image 328
piterio Avatar asked Nov 10 '15 13:11

piterio


1 Answers

Finally I got a solution few days ago. So, I will answer my question for this one who want to know.

JS:

var file = $("#file").files[0]; //this is the input where I can choose the file
var formData = new FormData();
formData.append('file', file);

var xhr = new XMLHttpRequest();
xhr.open('POST', '/myWebServiceUrl');
xhr.onload = function () {
    //TODO show the progress
};

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        //TODO success callback
    }
};

xhr.upload.onprogress = function (event) {
    //TODO show the progress
};

xhr.send(formData);

JAVA:

Part filePart = request.getPart("file");
String fileName = String.valueOf("fileName");
File file = new File("/the/path/" + fileName);
OutStream outFile = new FileOutputStream(file);
InputStream filecontent = filePart.getInputStream();

int read = 0;
byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
    outFile.write(bytes, 0, read);
}

If you want more information, just ask. I hope this will help you!!

like image 100
piterio Avatar answered Oct 07 '22 16:10

piterio