2013-02-12 36 views
2

將上載文件寫入磁盤時java.io.FileNotFoundException Glassfish似乎在路徑中添加了額外的內容我也想保存圖像文件,有沒有一些方法可以使用我的servlet獲取的絕對路徑通過getRealPath()

String appPath = request.getServletContext().getRealPath("");

我花了幾天的時間嘗試不同的方法來上傳圖像文件,並讓servlet將其保存到磁盤。

我用這個例子: http://www.codejava.net/java-ee/servlet/how-to-write-upload-file-servlet-with-servlet-30-api

使用調試I可以看到的文件名和路徑信息被正確收集,但代碼失敗在`part.write(savePath +文件分割符+文件名);``

和GlassFish的異常報告:

exception 

java.io.FileNotFoundException: C:\Program Files\glassfish-3.1.2.2\glassfish\domains\domain1\generated\jsp\com.onemore_onemore-web_war_1.0-SNAPSHOT\D:\Dropbox\Git\Brian_JEE\onemore\onemore\onemore-web\target\onemore-web-1.0-SNAPSHOT\image\screengrab_all_products.jpg (The filename, directory name, or volume label syntax is incorrect) 

我可以看到正確的路徑作爲此異常的一部分D:\Dropbox\Git\Brian_JEE\onemore\onemore\onemore-web\target\onemore-web-1.0-SNAPSHOT\image\screengrab_all_products.jpg

JSP

<form action="${pageContext.request.contextPath}/imageupload" method="post" enctype="multipart/form-data" name="productForm" id="productForm"> 
<input type="file" name="file" id="file"> 
<input type="submit" name="Submit" value="Submit"></td> 
</form> 

的Servlet

@WebServlet(name = "UploadImageServlet", urlPatterns = {"/imageupload"}) 
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB 
maxFileSize = 1024 * 1024 * 10, // 10MB 
maxRequestSize = 1024 * 1024 * 50) // 50MB 
public class UploadImageServlet extends HttpServlet { 

    /** 
    * Name of the directory where uploaded files will be saved, relative to the 
    * web application directory. 
    */ 
    private static final String SAVE_DIR = "image"; 

    /** 
    * handles file upload 
    */ 
    @Override 
    protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // gets absolute path of the web application 
     String appPath = request.getServletContext().getRealPath(""); 
     // constructs path of the directory to save uploaded file 
     String savePath = appPath + File.separator + SAVE_DIR; 

     // creates the save directory if it does not exists 
     File fileSaveDir = new File(savePath); 
     if (!fileSaveDir.exists()) { 
      fileSaveDir.mkdir(); 
     } 

     for (Part part : request.getParts()) { 
      String fileName = extractFileName(part); 
      part.write(savePath + File.separator + fileName); 
     } 

     request.setAttribute("message", "Upload has been done successfully!"); 
     getServletContext().getRequestDispatcher("/WEB-INF/jsp/newproduct.jsp").forward(
       request, response); 
    } 

    /** 
    * Extracts file name from HTTP header content-disposition 
    */ 
    private String extractFileName(Part part) { 
     String contentDisp = part.getHeader("content-disposition"); 
     String[] items = contentDisp.split(";"); 
     for (String s : items) { 
      if (s.trim().startsWith("filename")) { 
       return s.substring(s.indexOf("=") + 2, s.length() - 1); 
      } 
     } 
     return ""; 
    } 
} 

回答

4

切勿使用getRealPath()

你不應該保存在部署文件夾上傳的文件。我之前已經解釋過很多次了。其中一個解釋可以在這個答案中找到:Uploaded image only available after refreshing the page

任何使用getRealPath()方法的博客/文章中找到的任何JSP/Servlet代碼片段都應該帶上一大袋鹽。它的質量和作者的知識應該受到質疑。 There is namely no sensible real world use case for that method

將上傳的文件保存在deploy文件夾外的固定路徑中。另見How do I set the folder for storing file uploads using Commons FileUpload

+0

謝謝你的回答。我已經閱讀了許多帖子,現在我的圖片位於deploy文件夾的外面,並在'glassfish-web.xml'中設置了一個新屬性'alternatedocroot_1',它可以正確映射圖像以供顯示。不幸的是,無論我輸入什麼路徑,我的'part.write'都堅持將文件寫入錯誤的文件夾。你能告訴我如何讓'write.part'將文件保存到我設置的文件夾中。 謝謝 – 2013-02-13 14:57:01

+0

確保路徑以前導斜槓開始:'part.write(「/ path/to/filename.ext」)'。 – BalusC 2013-02-13 15:00:57

+1

謝謝。讀完@MultipartConfig註解後,我發現我可以用'location =「****」設置路徑''文件成功上傳到我想要的文件夾,然後glassfish報告一個異常(文件訪問被拒絕)。儘管至少該文件是在正確的地方。 – 2013-02-13 15:40:34

相關問題