Java servlet将文件上传到“Web Pages”文件夹

时间:2015-12-03 13:55:24

标签: 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
        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");
        }
    }

我尝试将img上传到WEB-PAGES文件夹。有可能吗?

此文件夹的结构为:

Web Pages
         WEB-INF
         img
         upload.jsp

但是我总是这样做:

File Upload Failed due to java.io.FileNotFoundException: 
The system can not find the path

适用于路径C:\uploadFolder但不能上传到Web Pages文件夹的代码。

为什么?

1 个答案:

答案 0 :(得分:1)

您想上传到您的网络应用程序,以便您可以再次下载该文件吗?对于一些ServletEngines

servletRequest.getSession().getServletContext().getRealPath("/")

解析为“真正的”文件系统路径(如果应用程序已部署爆炸,等等......)