user1007522
user1007522

Reputation: 8118

Tomcat saving file gives exception

I'm trying to save an uploaded file to my disk like this:

   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 always gives me the exception:

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)

I don't know why it isn't working. Someone that can help me?

Upvotes: 0

Views: 715

Answers (2)

StanislavL
StanislavL

Reputation: 57421

Call uploads.mkdirs(); before the new file creation

 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.

Upvotes: 2

Bruno Marco Visioli
Bruno Marco Visioli

Reputation: 418

Check with uploads.getAbsolutePath() to see if it's mapping the relative path to the intended folder. If yes, see if the account running tomcat has read/write access to the folder.

Upvotes: 0

Related Questions