0

我在我的注册表单中上传用户图像。我想将它保存在图像文件夹中。如果给定绝对路径,我的应用程序正在工作,但如何给路径相对方式。这是我的代码。//检查多部分内容* // 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
4

1 回答 1

1

好吧,在 Java EE 应用程序中使用相对路径并不容易,因为有时它们可​​能会引用 IDE 的根文件夹,并且由于每个 JSP 文件都被编译为 IDE 或 Tomcat 工作目录中的 java 文件,它们可能会使用该路径作为相对路径。

我在 Eclipse 中编码时遇到了同样的问题。

这个问题的解决方案是在 web.xml 中编码绝对路径,或者作为上下文参数(或)init-parameters,如果您将来想要更改目录,它将是一个地方的更改。

于 2013-03-13T12:33:08.820 回答