如何使用JSP/Servlet将文件上传到服务器?我试过这个:
<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
但是,我只获取文件名,而不是文件内容.当我添加 enctype="multipart/form-data"到<form>,然后request.getParameter()返回null.
在研究期间,我偶然发现了Apache Common FileUpload.我试过这个:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.
Run Code Online (Sandbox Code Playgroud)
不幸的是,servlet抛出了一个没有明确消息和原因的异常.这是堆栈跟踪:
SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at …Run Code Online (Sandbox Code Playgroud) 我正在创建一个JSP/Servlet Web应用程序,我想通过Ajax将文件上传到Servlet.我该怎么做呢?我正在使用jQuery.
我做到目前为止:
<form class="upload-box">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error" />
<input type="submit" id="upload-button" value="upload" />
</form>
Run Code Online (Sandbox Code Playgroud)
有了这个jQuery:
$(document).on("#upload-button", "click", function() {
$.ajax({
type: "POST",
url: "/Upload",
async: true,
data: $(".upload-box").serialize(),
contentType: "multipart/form-data",
processData: false,
success: function(msg) {
alert("File has been uploaded successfully");
},
error:function(msg) {
$("#upload-error").html("Couldn't upload file");
}
});
});
Run Code Online (Sandbox Code Playgroud)
但是,它似乎不发送文件内容.
我通过XmlHTTPRequest和HTML5上传多个文件.我上传工作正常,但我希望每个文件上传都有一个进度条.但是,我的代码使用最后一个进度条进行所有文件上传,而不是使用自己的进度条进行每次上传.所以这主要是客户端的视觉效果,但它真的很烦我.出于某种原因,我假设附加文件上传进度的事件会覆盖自己并使用最后一个进度条.这是我的代码:
var files = event.dataTransfer.files;
// iterate over each file to upload, send a request, and attach progress event
for (var i = 0, file; file = files[i]; i++) {
var li = $("<li>" + file.name + "<div class='progressbar'></div></li>");
// add the LI to the list of uploading files
$("#uploads").append(li);
// fade in the LI instead of just showing it
li.hide().fadeIn();
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
var percent = parseInt(e.loaded / e.total * 100);
li.find(".progressbar").width(percent);
}, false); …Run Code Online (Sandbox Code Playgroud) file-upload ×3
jsp ×2
servlets ×2
ajax ×1
html5 ×1
java ×1
java-ee ×1
jquery ×1
progress-bar ×1