【问题标题】:How to send a file from JavaScript to a Java WebService如何将文件从 JavaScript 发送到 Java WebService
【发布时间】:2016-02-11 09:46:42
【问题描述】:

我有一个 HTML5 应用程序,使用 Cordova,您可以从您的设备上传文件(图像和视频)。而且我必须将用户上传的这个文件发送到Java WebService,然后再上传到服务器。

我需要帮助,因为我无法实现我想要的。我尝试了几种在 Internet 上找到的解决方案,但都没有成功。

WeService 返回下一个异常

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

这是我现在的代码

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);                
        }
    }
}

我非常感谢各种帮助。

【问题讨论】:

  • 一个需要完整的客户端代码来调试..你提供的可能没有帮助!
  • 我有输入标签和问题中的 ajax 请求......你认为我还应该包括什么? @RayonDabre
  • 您应该为您的 ajax 请求设置正确的内容类型
  • 如果我设置 contentType: "multipart/form-data" 我有同样的例外:( @PieterWillaert
  • @piterio,您的 JavaScript 中使用了许多选择器,例如 $("#uploadMedia")("#nombreMedia")#entityId。怎么会知道他们在做什么? don't just copy in your entire program

标签: javascript java android web-services cordova


【解决方案1】:

几天前我终于找到了解决方案。所以,我将为这个想知道的人回答我的问题。

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);
}

如果您想了解更多信息,请询问。希望对你有帮助!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2011-07-03
    • 2013-09-07
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多