Shekar
Shekar

Reputation: 159

java.io.FileNotFoundException: C:\Users\user\AppData\Local\Temp (Access is denied)

When I upload files to local system's temp directory from Mozilla Browser I get Access denied error. But if I do the same thing from Eclipse Browser I dont see any error, means it is uploading without any error:

Code:

for (Part part : request.getParts()) {
     fileName = getFileName(part);
     part.write(System.getProperty("java.io.tmpdir") + fileName);
}


private String getFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    System.out.println("content-disposition header= "+contentDisp);
    String[] tokens = contentDisp.split(";");
    for (String token : tokens) {
        if (token.trim().startsWith("filename")) {
            return token.substring(token.indexOf("=") + 2, token.length()-1);
        }
    }
    return "";

Error:

java.io.IOException: java.io.FileNotFoundException: C:\Users\user\AppData\Local\Temp (Access is denied)

Allan, this is the code:

final String path = System.getProperty("java.io.tmpdir");
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();

    try {

        for (Part part : request.getParts()) {
            String fileName = getFileName(part);

            out = new FileOutputStream(new File(path , fileName));
            filecontent = part.getInputStream();

            int read = 0;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            File UploadedFile = new File(path + File.separator + fileName);
            UploadedFile.delete();
       }

    } catch (FileNotFoundException fne) {

        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");


    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }

Upvotes: 1

Views: 7982

Answers (3)

Navneet Gupta
Navneet Gupta

Reputation: 1

Same problem I was facing few minutes ago. Your code won't work for file upload with other request parameter together.

when you're calling getParts() it takes other parameters also as parts.

  1. Now in case of file taken as part content-dipsosition header has

form-data; name="<file-parameter-name>"; filename="<filename>"

A thing to be noted <filename> may be different if submitted from different browser. Try to submit it from eclipse's in built browser. Try to print and see content-disposition header by System.out.println(part.getHeader("content-disposition"));

  1. In case of your loop runs for other parameters taken as part, content-disposition has

form-data; name=""

Now see there is nothing like filename="", so your function to get filename returns null.

Now you calls part.write() but inside only path is passed not filename as function you called to get filename returns null. So you get exception even thought it actually uploads file.

After getting filename put a condition

if(filename.equals("")){continue;} But that's also not a good solution as loop iterate for no reason for other parameter.

Upvotes: 0

Allan Braga
Allan Braga

Reputation: 470

See this example, when create the file use two parameter as the example:

File scratchFile = new File(System.getProperty("java.io.tmpdir"), "filename.tmp");

Example:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    // Create path components to save the file
    final String path = System.getProperty("java.io.tmpdir");
    final Part filePart = request.getPart("file");
    final String fileName = getFileName(filePart);

    OutputStream out = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();

    try {
        //File Temp here with two parameters
        out = new FileOutputStream(new File(path , "filename.tmp"));

        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        writer.println("New file " + fileName + " created at " + path);


    } catch (FileNotFoundException fne) {

        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        writer.println("<br/> ERROR: " + fne.getMessage());

    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

And your method:

private String getFileName(final Part part) {
      final String partHeader = part.getHeader("content-disposition");
      LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
      for (String content : part.getHeader("content-disposition").split(";")) {
          if (content.trim().startsWith("filename")) {
              return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
          }
      }
      return null;
}

References:

Permission

Upload Method

Upvotes: 1

Maksim
Maksim

Reputation: 521

In case of a web application, the Webcontainer might have set some SecurityManager (https://docs.oracle.com/javase/8/docs/api/java/lang/SecurityManager.html) to block write access to the local file system. Check if this has been the case...

Upvotes: 0

Related Questions