我已经实施了拖放功能在jsp和servlet中删除文件上传,但是我遇到了问题。以下是我的upload.jsp
代码的一部分:
function dropUpload(event) {
var files = event.dataTransfer.files;
upload(files);
}
function upload(files) {
var formData = new FormData();
for (var i in files) {
formData.append('file[]', files[i]);
}
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.open("POST", "UploadServlet");
xhr.send(formData);
}
我在getParts()
代码中使用UploadServlet.java
方法获取用户上传的文件,如下所示:
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String savePath = "D:\\TEST";
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
response.getWriter().println(request.getParts().size());
for (Part part : request.getParts()) {
if(part.getContentType() == null) {
continue;
}
response.getWriter().println("Part name: " + part.getName());
response.getWriter().println("Size: " + part.getSize());
response.getWriter().println("Content Type: " + part.getContentType());
String fileName = extractFileName(part, response);
response.getWriter().println(fileName);
part.write(savePath + File.separator + fileName);
response.getWriter().println("already upload file:" + fileName);
response.getWriter().println("=============================================");
}
}
private String extractFileName(Part part,HttpServletResponse response) throws IOException {
String contentDisp = part.getHeader("content-disposition");
//response.getWriter().println(contentDisp);
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
但我无法理解,如果我使用upload.jsp
上传2个文件,
getParts().size()
的值为4;这意味着我总是有2个文件,而不是我上传的文件,2个外部文件名和contentType将为null,这将导致part.write()
中的错误。
我的解决方案是使用if语句
if(part.getContentType() == null) {
continue; }
忽略空文件。
有人能告诉我为什么会这样吗?