通过getRealPath()将上载文件写入磁盘时出现java.io.FileNotFoundException [英] java.io.FileNotFoundException when writing uploaded file to disk via getRealPath()

查看:559
本文介绍了通过getRealPath()将上载文件写入磁盘时出现java.io.FileNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Glassfish似乎也增加了额外的路径我想要保存我的图像文件,是否有一些方法来使用我的servlet获得的绝对路径



String appPath = request.getServletContext()。getRealPath();



方法来上传一个图像文件,并有一个servlet保存到磁盘。

我使用这个例子:
http://www.codejava.net/java-ee/使用调试我可以看到文件的名称和路径信息被正确地收集,但代码在`part.write(savePath + File.separator + fileName);`失败```

和glassfish的异常报告是:

 异常

java.io.FileNotFoundException:C:\程序文件\glassfish-3.1.2.2\ glassfish\\ domains\domain1\generated\jsp\com.onemore_onemore-web_war_1.0-SNAPSHOT\D:\Dropbox\Git\Brian_JEE\onemore\onemore\onemore-web\target\ onemore-web-1.0-SNAPSHOT\image\screengrab_all_products.jpg(文件名,目录名或卷标语法不正确)

我可以看到正确的路径作为这个异常的一部分 D:\Dropbox\Git\Brian_JEE\onemore\onemore\onemore-web\target \ onemore-web-1.0-SNAPSHOT\image\screengrab_all_products.jpg



JSP

 < form action =$ {pageContext.request.contextPath} / imageuploadmethod =postenctype =multipart / form-dataname =productForm ID = productForm > 
< input type =filename =fileid =file>
< input type =submitname =Submitvalue =Submit>< / td>
< / form>

Servlet

  @WebServlet(name =UploadImageServlet,urlPatterns = {/ imageupload})
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,// 2MB
maxFileSize = 1024 * 1024 * 10,// 10MB
maxRequestSize = 1024 * 1024 * 50)// 50MB
public class UploadImageServlet extends HttpServlet {
$ b $ / **
*上传的文件将保存在相对于
* web应用程序目录中。
* /
private static final String SAVE_DIR =image;
$ b / **
*处理文件上传
* /
@Override $ b $保护无效doPost(HttpServletRequest请求,
HttpServletResponse响应)throws ServletException,IOException {
//获取Web应用程序的绝对路径$ b $ String appPath = request.getServletContext()。getRealPath();
//构建保存上传文件的目录路径
String savePath = appPath + File.separator + SAVE_DIR;

//创建保存目录(如果不存在)
文件fileSaveDir = new File(savePath);
if(!fileSaveDir.exists()){
fileSaveDir.mkdir();

$ b $(部分:request.getParts()){
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}

request.setAttribute(message,Upload has done done!);
getServletContext()。getRequestDispatcher(/ WEB-INF / jsp / newproduct.jsp)。forward(
request,response);

$ b / **
*从HTTP标头内容处理中提取文件名
* /
private String extractFileName(Part part){
String contentDisp = part.getHeader(content-disposition);
String [] items = contentDisp.split(;);
for(String s:items){
if(s.trim()。startsWith(filename)){
return s.substring(s.indexOf(=)+ 2,s.length() - 1);
}
}
return;


$ / code $ / pre

解决方案

使用getRealPath()



您不应该将上传的文件保存在deploy文件夹中。之前我已经解释过这么多次了。其中一个解释可以在这个答案中找到:已上传图片仅在刷新页面后才可用。



任何使用的博客/文章中找到的任何JSP / Servlet代码片段getRealPath ()方法应该用一大袋盐。质量和作者的知识应该受到质疑。 这种方法现在还没有明智的现实世界用例

将上传的文件保存在deploy文件夹外的固定路径中。另见如何使用Commons FileUpload设置存储文件上传的文件夹


Glassfish seems to be adding extra to the path I want to save my image file too, is there some way to use only the absolute path my servlet gets with

String appPath = request.getServletContext().getRealPath("");?

I have spent days trying different methods to upload an image file and have a servlet save it to disk.

I used this example: http://www.codejava.net/java-ee/servlet/how-to-write-upload-file-servlet-with-servlet-30-api

Using debug I can see the file name and path information is collected correctly but the code fails at `part.write(savePath + File.separator + fileName);``

And glassfish's exception report is:

exception

java.io.FileNotFoundException: C:\Program Files\glassfish-3.1.2.2\glassfish\domains\domain1\generated\jsp\com.onemore_onemore-web_war_1.0-SNAPSHOT\D:\Dropbox\Git\Brian_JEE\onemore\onemore\onemore-web\target\onemore-web-1.0-SNAPSHOT\image\screengrab_all_products.jpg (The filename, directory name, or volume label syntax is incorrect)

I can see the correct path as part of this exception D:\Dropbox\Git\Brian_JEE\onemore\onemore\onemore-web\target\onemore-web-1.0-SNAPSHOT\image\screengrab_all_products.jpg

JSP

<form action="${pageContext.request.contextPath}/imageupload" method="post" enctype="multipart/form-data" name="productForm" id="productForm">
<input type="file" name="file" id="file">
<input type="submit" name="Submit" value="Submit"></td>
</form>

Servlet

@WebServlet(name = "UploadImageServlet", urlPatterns = {"/imageupload"})
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB 
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)   // 50MB
public class UploadImageServlet extends HttpServlet {

    /**
     * Name of the directory where uploaded files will be saved, relative to the
     * web application directory.
     */
    private static final String SAVE_DIR = "image";

    /**
     * handles file upload
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
      // gets absolute path of the web application
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + SAVE_DIR;

        // creates the save directory if it does not exists
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }

        for (Part part : request.getParts()) {
            String fileName = extractFileName(part);
            part.write(savePath + File.separator + fileName);
        }

        request.setAttribute("message", "Upload has been done successfully!");
        getServletContext().getRequestDispatcher("/WEB-INF/jsp/newproduct.jsp").forward(
                request, response);
    }

    /**
     * Extracts file name from HTTP header content-disposition
     */
    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
}

解决方案

Never use getRealPath()

You should not save uploaded files in the deploy folder. I have explained this so many times before. One of those explanations can be found in this answer: Uploaded image only available after refreshing the page.

Any JSP/Servlet code snippet found on some blog/article which ever uses the getRealPath() method should be taken with a huge bag of salt. Its quality and the knowledge of the author should strongly be questioned. There is namely no sensible real world use case for that method.

Save uploaded files in a fixed path outside the deploy folder. See also How do I set the folder for storing file uploads using Commons FileUpload.

这篇关于通过getRealPath()将上载文件写入磁盘时出现java.io.FileNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆