java - 如何在简单的jsp文件上传中设置临时目录相对路径? FIleNotFound 异常

标签 java jsp servlets file-upload filepath

<分区>

我正在用 jsp 做一个简单的文件上传。我似乎已经被这个简单的路径问题阻止了。我在 Windows 上开发,但可能会部署在 Linux 机器上。所以我在 mywebsite/tempfiledir 和 mywebsite/finalfiledir 下有 tmpdir 和 finaldir

所以我使用这段代码(servlet 的片段)

public class SyncManagerServlet extends HttpServlet {
 private static final String TMP_DIR_PATH = "/tempfiledir";
 private File tempDir;
 private static final String DESTINATION = "/finalfiledir";
 private File destinationDir;

 public void init(ServletConfig config){
    try {
        super.init(config);

        tempDir = new File(getAbsolute(TMP_DIR_PATH));

        if(!tempDir.isDirectory()){
            throw new ServletException(TMP_DIR_PATH + " is not a Directory");
        }

        destinationDir = new File(getAbsolute(DESTINATION));
        if(!destinationDir.isDirectory()){ 
            throw new ServletException(DESTINATION + " is not a Directory");
        }

    } catch (ServletException ex) {
        Logger.getLogger(OrliteSyncManagerServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String email = request.getParameter("email");
    String path = request.getContextPath();
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    fileItemFactory.setRepository(tempDir);
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);


    try {


        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while(itr.hasNext()){
            FileItem item = (FileItem) itr.next();

            if( item.isFormField() && item != null ){

                out.println("<html>");
                out.println("<head>");
                out.println("<body>");
                out.println("your email: " + item.getString() + " has been submited and context path is "+ request.getContextPath() );
                out.println("</body>");
                out.println("</head>");
                out.println("</html>");

            } else {
                out.println("the uploaded file name is  : " + item.getName());
                out.println("content type  is  : " + item.getContentType());
                out.println("Size  is  : " + item.getSize());
                File file = new File(destinationDir, FilenameUtils.getName(item.getName()));

                item.write(file);
            }

public String getAbsolute(String relativepath){
    return getServletContext().getRealPath(relativepath);
}


//......
}

我有这个异常(exception)

java.io.FileNotFoundException: D:\WORK\java\netbeansProject\Projects\mywebsite-webapp\target\mywebsite\finalfiledir (Access is denied)

我不明白为什么相对路径失败了。 我注意到在很多在线示例中,人们使用 tempdir 的完整路径。 所以在我不得不担心 linux 部署的情况下,解决方法是什么?但首先我想了解为什么我给出的路径是错误的。

感谢阅读本文! 所以这里有 2 个问题

1 如何解决这个路径即时问题?

2 如何以更便携的方式做到这一点(考虑到 linux 特权)?

谢谢!

最佳答案

1 how to solve this path immediate issue?

以斜杠开头的路径与当前工作目录无关。它们是绝对的,并且仅在 Windows 中指向当前工作磁盘(服务器正在运行并取决于服务器的启动方式)。

在你的例子中,"/tempfiledir"在 Windows 中会指向 C:\tempfiledir当 Windows 和服务器安装在 C:\ 上时, 在 Linux 中为 /tempfiledir .您需要在 init() 中添加另一个检查执行 File#exists() 的方法还要检查及时发现文件夹的缺失。

2 how to do it in a more portable way (with linux privileges in mind)?

只要您不使用 Windows 特定的磁盘标签,例如 C:\并使用 /作为路径分隔符,您无需担心这一点。

如果你真的坚持要将文件写入webcontent,那么你需要记住两点:1)部署为WAR时,只有在WAR被servletcontainer扩展时才有效。 2) 重新部署 WAR 时,所有内容(所有上传的文件)都将被删除。

这是将相对 Web 路径转换为绝对磁盘文件系统路径的方式,以便您可以在 File 中进一步使用它和配偶:

String relativeWebPath = "/tempfiledir";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath, filename);

与问题无关:item.getName()将在某些网络浏览器(特别是:MSIE 系列)中返回完整的客户端路径。根据 Commons Fileupload FAQ你需要调用FilenameUtils#getName()new File() 中用作文件名之前在其上,否则也会在那里造成破坏。

关于java - 如何在简单的jsp文件上传中设置临时目录相对路径? FIleNotFound 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4258345/

相关文章:

java - 将 TripleDES 算法从 .Net 应用于 Java 时出错

java - 如何在ArrayList中找到重复次数最多的字符串?

java - Jenkins 中的 Sonar 未拾取 Jacoco.exec 文件

javascript - 这是否被视为 POST 或 GET 请求?

java - Spring Framework 中的 NullPointerException(或什么?)

java - 如何编写需要 Android 上下文的集成测试?

java - 当我运行 jsp 页面时,没有显示图像。为什么?

jsp - 如何检查 ArrayList 是否为空或不使用 c :if in JSTL?

javascript - 从子窗口调用操作,关闭子窗口并重新加载父页面

java - 如何更改Java Filter中的HTTP响应内容长度 header