2
即時通訊嘗試使用org.apache.commons.fileupload上傳文件。但我不,不知道,我犯了什麼錯誤讓我的servlet中出現以下錯誤。請任何人幫助我在這..這是我得到的錯誤。使用Apache commans的文件上傳問題在JSP/Servlet中的文件上傳API
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:199)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:361)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
upload1.doPost(upload1.java:34)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
這是我的servlet代碼
if (ServletFileUpload.isMultipartContent(req)) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) {
// process only file upload - discard other form item types
if (item.isFormField()) continue;
String fileName = item.getName();
// get only the file name not whole path
if (fileName != null) {
// fileName = FilenameUtils. getName(fileName);
}
}
} catch (Exception e) {
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An error occurred while creating the file : " + e.getMessage());
}
} else {
res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
"Request contents type is not supported by the servlet.");
}
和形式
<form method="POST" action="upload1" enctype="multipart/form-data" >
感謝ü
非常感謝你的回覆..我這樣做.. – bHaRaTh 2011-03-25 17:09:38
非常感謝你非常BalusC ..抱歉,問這樣一個愚蠢的問題。我忘了在我的課程路徑中添加commons IO jar ...但另一個問題是即時消息打印文件名,但它沒有顯示完整的路徑名。 – bHaRaTh 2011-03-25 17:24:32
沒問題。希望你至少學會了如何解釋例外。至於文件名,完整的路徑應該不是**你的興趣。更有甚者,你[應該](http://commons.apache.org/fileupload/faq.html#whole-path-from-IE)使用'FilenameUtils.getName(item.getName())'因爲越野車MSIE瀏覽器發送完整路徑!路徑是無用的。用'item.getInputStream()'獲取文件內容作爲'InputStream'。另請參閱[這個答案](http://stackoverflow.com/questions/81180/how-to-get-the-file-path-from-html-input-form-in-firefox-3/3374408#3374408)。 – BalusC 2011-03-25 17:26:23