2017-02-25 64 views
0

我使用完成文件上傳任何文件上傳:的servelt使用的contextPath和參數servletContext上傳成功下載不能下載

    ServletContext servletContext = getServletContext(); 
     String contextPath = servletContext.getRealPath(File.separator); 

     String path = contextPath + "\\uploads\\" + session.getAttribute("seusername"); 
     System.out.println(path); 

     File file=new File(path); 
     if(!file.exists()) 
      file.mkdirs(); 
     Part filePart = request.getPart("uploadfile"); 
     //return content type of the file 
     String type = filePart.getHeader("content-type"); 

     //checking content type of file. 
     if (!type.equals("application/x-msdownload")) { 

      final String fileName = getFileName(filePart); 
      myfilename=fileName; 
      try { 
       EncriptFilename= aESCryp.encrypt(fileName); 
       System.out.println(EncriptFilename); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


      OutputStream fout = null; 
      InputStream filecontent = null; 

      try { 
       fout = new FileOutputStream(new File(path + File.separator + fileName)); 
       filecontent = filePart.getInputStream(); 
       int read = 0; 
       final byte[] bytes = new byte[32 * 1024]; 

       while ((read = filecontent.read(bytes)) != -1) { 
        fout.write(bytes, 0, read); 
       } 

       fout.flush(); 
       fout.close(); 
      } catch (Exception er) { 
       System.out.println("error:"+er.getMessage()); 
      } 
     } 

我上傳的圖片,PDF,DOC文件,其,,,是很好.. 後我的本地光盤文件夾上的文件位置。 d:\ JavaWorkspace.metadata.plugins \ org.eclipse.wst.server.core \ TMP1 \ wtpwebapps \文件\上傳\用戶\ java_coffee_cup_logo1600.png

我的問題是...如何下載這個文件,, , 我不能用href鏈接下載..

回答

0

您的網絡應用程序可以支持文件下載,基本上做與您的文章Servlet做的相反。

創建一個「下載」Servlet,並在您的web.xml中配置到Servlet的映射(或使用註釋來定義映射)。該URL到這個servlet可能看起來像: http://machine.com/my-app/download/my-file.jpg

在下載Servlet,看看請求的URL發現所請求的文件名(my-file.jpg),然後用FileInputStream打開和讀取my-file.jpgrequest.getPathInfo()可能會爲您提供確定用戶想要下載的文件所需的信息。查看javadoc for HttpServletRequest.getPathInfo().

請注意,my-file.jpg可以存在任何你想要的。您的Servlet可以將請求URL中的文件名和路徑映射到本地文件系統上的任意位置。該文件甚至可以存在於另一臺Web服務器上。您只需要能夠創建一個訪問該文件的InputStream

使用該文件的路徑信息,創建一個FileInputStream來訪問該文件。然後將FileInputStream複製到ServletResponse的輸出流。這SO post和這SO post舉例說明如何將InputStream複製到OutputStream

你可以得到如下響應的輸出流:response.getOutputStream()。完成後請不要忘記關閉InputStreamOutputStream