Tomcat保存文件提供异常

时间:2015-01-19 12:51:03

标签: java tomcat

我正在尝试将上传的文件保存到我的磁盘上,如下所示:

   Part filePart = req.getPart("pic");
    String fileName = filePart.getSubmittedFileName();
    InputStream fileContent = filePart.getInputStream();

    File uploads = new File("/images/gin");
    File file = new File(uploads, fileName);
    if(!file.exists())
        file.createNewFile();
    Files.copy(fileContent, file.toPath());

Tomcat总是给我一个例外:

java.io.IOException: No such file or directory
    java.io.UnixFileSystem.createFileExclusively(Native Method)
    java.io.File.createNewFile(File.java:1006)
    com.springapp.mvc.servlets.AddItemServlet.doPost(AddItemServlet.java:39)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

我不知道为什么它不起作用。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

在新文件创建之前调用uploads.mkdirs();

 mkdirs()

 * Creates the directory named by this abstract pathname, including any
 * necessary but nonexistent parent directories.  Note that if this
 * operation fails it may have succeeded in creating some of the necessary
 * parent directories.

答案 1 :(得分:0)

选中uploads.getAbsolutePath(),查看它是否映射到目标文件夹的相对路径。如果是,请查看运行tomcat的帐户是否具有该文件夹的读/写权限。