最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to send a file from JavaScript to a Java WebService - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Nov 10, 2015 at 16:20 piterio asked Nov 10, 2015 at 13:36 piteriopiterio 8101 gold badge8 silver badges24 bronze badges 6
  • One will need entire client side code to debug..What you have provided may not help! – Rayon Commented Nov 10, 2015 at 13:41
  • I have the input tag, and the ajax request in my question... What else do you think I should include? @RayonDabre – piterio Commented Nov 10, 2015 at 13:46
  • you should set a correct content-type for your ajax-request – Pieter Willaert Commented Nov 10, 2015 at 14:03
  • If I set contentType: "multipart/form-data" I have the same exception :( @PieterWillaert – piterio Commented Nov 10, 2015 at 14:05
  • @piterio, There are many selectors used in your JavaScript for example $("#uploadMedia"), ("#nombreMedia")and #entityId. How one will know what are they doing ? don't just copy in your entire program – Rayon Commented Nov 10, 2015 at 15:35
 |  Show 1 more comment

1 Answer 1

Reset to default 15

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

发布评论

评论列表(0)

  1. 暂无评论