我想在将文件上传到我在localhost上运行的服务器时获得java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
。这是我正在使用的servlet:
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String UPLOAD_DIRECTORY = "~/EclipseProjects/DocSearch/uploads";
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(ServletFileUpload.isMultipartContent(request)) {
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item: multiparts) {
if(!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
request.setAttribute("message", "File uploaded successfully");
} catch (Exception ex) {
request.setAttribute("message", "File upload failed due to: " + ex);
}
} else {
request.setAttribute("message", "Sorry this servlet only handles file upload requests");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
我已经将commons-fileupload-1.2.2.jar添加到WEB-INF / lib文件夹中。我尝试创建一个新服务器并在其上运行项目,尝试从不同来源重新下载jar文件,但它们似乎都没有解决我的问题。
注意:
我已经经历过:
答案 0 :(得分:1)
您必须将commons-fileupload.jar
包含在项目依赖库文件夹中。
从官方网站http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi或maven网站获取commons-fileupload.jar
:http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload/1.3.1
如果您使用maven将此依赖项添加到pom.xml
:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>