2017-02-25 41 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