-1

I am trying to upload a file through my web application and read the uploaded file. First I can upload it to my desktop. But this is not what I want. I want to create a directory named file (you can see in picture) inside my project explorer in Eclipse. And then upload the file to there. I tried many ways to give the path but it always giving me this exception : File Upload Failed due to java.io.FileNotFoundException.Here is my project explorer.enter image description here

https://ibb.co/niTaN6 here is the image

And here is my code.

package com.fileupload;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;
@WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "/GraphCoverage/file/";

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

// process only if its multipart content
if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

           for (FileItem item : multiparts) {
           if (!item.isFormField()) {
           String name = new File(item.getName()).getName();
           item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
           }
        }

        // File uploaded successfully
        request.setAttribute("message", "Your file has been uploaded!");
        } 
        catch (Exception e) 
        {
         request.setAttribute("message", "File Upload Failed due to " + e);
        }
} else 
{
request.setAttribute("message", "This Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
  • Did you use full path of directory instead of relative path ? – Rohit Dec 23 '17 at 18:03
  • You mean like using C:\Users\Name\workspace\GraphCoverage\file ? – chalesea23 Dec 23 '17 at 18:05
  • Yes exactly full path till the directory where you want to place your file. – Rohit Dec 23 '17 at 18:07
  • Also whenever you are creating a file object trying using exists method of file object. It will return you true or false based on whether the path you provided exists or not. – Rohit Dec 23 '17 at 18:10
  • Rohit, But I don't want to give the relative path. Because it will make the project dependent to me. If someone tries to run in their pc, program wont find the path. So I want to upload inside the folder I created in project explorer. – chalesea23 Dec 23 '17 at 18:16
  • Ideally you should externalize your upload directory. Create a properties file and add a new property named "uploadDirPath" and provide some value to it. This way every can have their custom path and your code will just read the directory location from property file. – Rohit Dec 23 '17 at 18:18
  • Externalizing the location directory will help you and everyone else who uses the you application. And they can always have directory of their choice instead of the one which you are providing... – Rohit Dec 23 '17 at 18:21
  • I need a path to create a upload directory. What if that directory does not exist in anyone except me ? new File("/path/directory").mkdirs(); – chalesea23 Dec 23 '17 at 18:35
  • Yes you can check if directory exists or not using new file("location").exists() method. If the does not exist then use mkdirs function to create it. – Rohit Dec 23 '17 at 18:37
  • @Rohit, to create a directory I found this code on stacowerflow again. it is created but I don't know where is the location.I am searching on my pc but could not foind it yet. Any idea?File theDir = new File("new folder"); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: " + theDir.getName()); boolean result = false; try{ theDir.mkdir(); result = true; } catch(SecurityException se){ //handle it } } – chalesea23 Dec 23 '17 at 19:04
  • Provide some proper path like new File(''C://test/test2") – Rohit Dec 23 '17 at 19:06
  • But that is not externalizing.Maybe person uses unix and don't have that path. – chalesea23 Dec 23 '17 at 19:09
  • Thats what i said. U should first create a properties file. Provide the directory path in that location. From ur program read the properties file and get directory location and put that in new File(). So if someone wants to use that in linux. They will change path in properties file. – Rohit Dec 23 '17 at 19:11
  • Okey you mean, if a user tries to run my program first they will change the properties file ? – chalesea23 Dec 23 '17 at 19:16
  • Yes atleast first time. Its like configuration setup. – Rohit Dec 23 '17 at 19:17

1 Answers1

0

Hi chalesea23 you need to provide full system path like "C:/Users/abc/eclipse-workspace/Test/file", then it will work. Because a folder in your eclipse is nothing but a folder on your PC.

Below is working for me.

package com.java;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.annotation.WebServlet;



@WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final String UPLOAD_DIRECTORY = "C:/Users/abc/eclipse-workspace/Test/file";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        // process only if its multipart content
        if (isMultipart) {
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                // Parse the request
                List<FileItem> multiparts = upload.parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        String name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    }
                }

                // File uploaded successfully
                request.setAttribute("message", "Your file has been uploaded!");
            } catch (Exception e) {
                request.setAttribute("message", "File Upload Failed due to " + e);
            }
        } else {
            request.setAttribute("message", "This Servlet only handles file upload request");
        }
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    }
}
  • Yes this works for me too. But I don't want to give the relative path. Because it will make the project dependent to me. If someone tries to run in their pc, program wont find the path. So I want to upload inside the folder I created in project explorer. – chalesea23 Dec 23 '17 at 18:36