当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: