Java servlet将文件上载到";网页;文件夹
我正在制作简单的上传servlet 我的代码是:Java servlet将文件上载到";网页;文件夹,java,servlets,file-upload,Java,Servlets,File Upload,我正在制作简单的上传servlet 我的代码是: private final int FILE_LENGHT = 150; private final String UPLOAD_DIRECTORY = "/img/"; . . . . . @Override public void uploadFile(HttpServletRequest request) { //process only if its multipart content
private final int FILE_LENGHT = 150;
private final String UPLOAD_DIRECTORY = "/img/";
.
.
.
.
.
@Override
public void uploadFile(HttpServletRequest request) {
//process only if its multipart content
if (ServletFileUpload.isMultipartContent(request)) {
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
File f = new File(item.getName());
String ex = suo.getFileExtension(f);
String name = suo.randomString(FILE_LENGHT) + "." + ex;
item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
//File uploaded successfully
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 request");
}
}
但我总是有例外:
File Upload Failed due to java.io.FileNotFoundException:
The system can not find the path
它适用于路径C:\uploadFolder
的代码,但不适用于上传到网页
文件夹
为什么?您想上传到您的Web应用程序中,以便再次下载该文件?对于一些服务引擎
servletRequest.getSession().getServletContext().getRealPath("/")
解析为“真实”文件系统路径(如果应用程序已部署,等等…是否要上载到Web应用程序中,以便再次下载该文件?对于某些ServletEngine,servletRequest.getSession().getServletContext().getRealPath(“/”)解析为“真实”文件系统路径(如果应用程序已部署或分解等…)@Jan谢谢,它可以工作!在你的网络应用程序中存储图像并不理想。相反,只需在你的网络应用程序之外使用一个特定的位置,并保持其可配置性。积分只是交易的一部分-通过接受回答,你会在某种程度上将该问题标记为“完成”,这样其他愿意帮助的人就不会被吸引到阅读和理解你的问题中,然后读了所有的评论之后才发现,它已经被处理好了。尽管如此,要点还是不错的。现在有了17个,你甚至可以对答案进行投票;-)
servletRequest.getSession().getServletContext().getRealPath("/")