【发布时间】: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