Reputation: 119
I am uploading user image in my registration form.I want to keep it in image folder.My application is working if given absolute path but how to give path relative way. here' my code . //chck if multipart content*// if (!ServletFileUpload.isMultipartContent(request)) //if1
{
request.setAttribute("error", "No file is selected for upload");
rd=request.getRequestDispatcher("error.jsp"); //dispatching to error page if no file is sent via request
rd.forward(request,response);
} //end of if1
//****Setting space and path where file will be uploaded on server*****//
DiskFileItemFactory factory = new DiskFileItemFactory(); //object of class defined in commons package
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(REQUEST_SIZE);
String uploadPath = "c://"+ File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
userbean.setUserimage(uploadPath);
if (!uploadDir.exists())//if2
{
uploadDir.mkdir();
} //end of if2
//*******check the type of form and process accordingly*****//
try
{ //try1
List formItems = upload.parseRequest(request);// parses the request's content to extract file data
Iterator iter = formItems.iterator();
//******* iterates over form's fields**********//
while (iter.hasNext()) //while1
{
FileItem item = (FileItem) iter.next();
// ********processes only fields that are not form fields*******//
if (!item.isFormField()) //if3
{
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
fileuploaded=true;
}//end of if3
Upvotes: 0
Views: 1037
Reputation: 113
Well, using relative paths in a Java EE application is not easy because sometimes they may refer to the IDE's root folder and as every JSP file is compiled to a java file in the working directory of the IDE or Tomcat, they may use that path as relative path.
I faced the same problem when I was coding in Eclipse.
The solution to this problem is coding the absolute path in web.xml, either as context parameters (or) init-parameters and it will be a one place change if you want to change the directory in future.
Upvotes: 1