我正在我的注册表单中上传用户图片。我想把它保存在图片文件夹中。如果给定绝对路径但我的应用程序是如何工作但是如何给出路径相对方式。 这是'我的代码。 // 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
答案 0 :(得分:1)
好吧,在Java EE应用程序中使用相对路径并不容易,因为有时它们可能会引用IDE的根文件夹,并且每个JSP文件都被编译为IDE或Tomcat的工作目录中的java文件,它们可能会使用那条路作为相对路径。
当我在Eclipse中编码时遇到了同样的问题。
此问题的解决方案是编写web.xml中的绝对路径,作为上下文参数(或)init-parameters,如果您希望将来更改目录,它将是一个地方更改。