這段代碼爲什麼不起作用?我總是得到size()= 0,只要我上傳文件。爲什麼這個簡單的文件上傳不起作用? JSF
XHTML文件: -
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Abc</title>
</h:head>
<h:body>
<center>
<form method="post" enctype="multipart/form-data" id="form" action="/upload/uploadFile">
<input type="file"/> <br/>
<input type="Submit" value="upload"/>
</form>
</center>
</h:body>
</html>
這是我的servlet: -
package servlets;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet(name="uploadFile", urlPatterns={"/uploadFile"})
public class uploadFile extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, FileUploadException {
System.out.println("executed!");
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
System.out.println(items.size());
for (FileItem item : items) {
if (!item.isFormField()) {
System.out.println("Name: " + item.getName());
System.out.println("Size: " + item.getSize());
System.out.println("Type: " + item.getContentType());
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (FileUploadException ex) {
ex.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (FileUploadException ex) {
ex.printStackTrace();
}
}
@Override
public String getServletInfo() {
return "Short description";
}
}
更新:
1)如果我只需要添加名稱= 「東西」 到input type = "file"
,那麼它工作正常。這背後有什麼邏輯? 2)如果我使用h:form而不是form,那麼它不起作用(即使我的actionListener方法沒有得到執行)。這背後有什麼原因?我讀過h:表單不是爲了處理多部分/表單數據請求而設計的。這是真的嗎?
試試這個線程可能拓展領域, [http://stackoverflow.com/questions/11954181/upload-insert-retrieve-and-display-image-using-jpa-jsf-mysql][1] [1]:http://stackoverflow.com/questions/11954181/upload-insert-retrieve-and-display-image-using-jpa-jsf-mysql – 2012-08-14 15:04:44