views:

491

answers:

1

I'd like to know how to specify an upload directory preferably a relative path to a directory under my WEB-CONTENT directory where I'd like to store uploaded files: I get an error when I specify the upload be store as:

**File saveFile = new File("/"+fileName);** please refer to code below

Error:

INFO: Server startup in 497 ms
java.io.IOException: The system cannot find the path specified
 at java.io.WinNTFileSystem.createFileExclusively(Native Method)
 at java.io.File.createNewFile(Unknown Source)
 at controller.UploadServlet.processUploadedFile(UploadServlet.java:86)
 at controller.UploadServlet.doPost(UploadServlet.java:61)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
 at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
 at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
 at java.lang.Thread.run(Unknown Source)
java.io.IOException: Access is denied
 at java.io.WinNTFileSystem.createFileExclusively(Native Method)
 at java.io.File.createNewFile(Unknown Source)
 at controller.UploadServlet.processUploadedFile(UploadServlet.java:86)
 at controller.UploadServlet.doPost(UploadServlet.java:61)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
 at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
 at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
 at java.lang.Thread.run(Unknown Source)

my code:

**
 * Instantiates SempediaHome Controller
 */
public class UploadServlet extends HttpServlet {

 /**
  * 
  * @param
  * @return
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

  // Create a factory for disk-based file items
  DiskFileItemFactory factory = new DiskFileItemFactory();

  // Set factory constraints
  //factory.setSizeThreshold(yourMaxMemorySize);
  factory.setRepository(new File("/tmp"));

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);

  // Set overall request size constraint
  //upload.setSizeMax(yourMaxRequestSize);

  // Parse the request
  try {
   List /* FileItem */ items = upload.parseRequest(request);
   Iterator iter = items.iterator();
   while (iter.hasNext()) {
       FileItem item = (FileItem) iter.next();

       if (item.isFormField()) {
           this.processFormField(item);
       } else {
           this.processUploadedFile(item);
       }
   }
  } catch (FileUploadException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 /**
  * 
  * @param
  * @return
  */
 public void processUploadedFile(FileItem item) throws IOException {

  // Process a file upload
  if (!item.isFormField()) {
      //String fieldName = item.getFieldName();
      String fileName = item.getName();
      //String contentType = item.getContentType();
      //boolean isInMemory = item.isInMemory();
      //long sizeInBytes = item.getSize();     
      try {
       File saveFile = new File("/"+fileName);
       saveFile.createNewFile();
    item.write(saveFile);
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

 /**
  * 
  * @param
  * @return
  */
 public void processFormField(FileItem item) {

 }

}
+3  A: 

In your servlet (or jsp):

String contextRoot = getServletContext().getRealPath("/")

returns the context root. So:

factory.setRepository(new File(contextRoot + "WEB-INF/tmp"));

(you'd better not put the tmp directory in a place accessible from the web)

Your exception means that your current OS user doesn't have permissions to write to the target directory. Make sure it was write permissions for the desired directory.

Bozho
@Bozho: `getRealPath()` is not a good idea, IMO. `/WEB-INF/tmp` will suffice. Moreover, he is getting a `Access is Denied` exception. Not sure if that would remain intact. Actually this post is a follow up of http://stackoverflow.com/questions/2323598/commons-fileupload-java-io-filenotfoundexception
Adeel Ansari
I also use getRealPath() if I need to find the physical root of the webapp. Just need to keep in mind that saving the files in there only works for exploded wars.
Yoni
@Adeel: You are completely wrong. Starting a file name with "/WEB-INF/.." will be an absolute path on Unix file systems and an illegal path on Windows. Even if it was a relative path, you have no guarantee that it is relative to the application deployment directory.
jarnbjo
+1. It's perfectly valid. I would however only mention that those files will get lost whenever you redeploy the webapp. If you want a bit more permanent storage of the files, rather store them on a fixed path *outside* the webapp, or maybe in a database.
BalusC