java文件下载

1.jsp实现的下载功能,图片,word,txt都可以下载

第一行代码中去掉contentType="application/x-msdownload"以后才可以下载,可以下载图片,word,tx文件都没问题。

<%@page language="java"     pageEncoding="gb2312"
	import="java.net.*,java.io.*"
%>
<%
      //关于文件下载时采用文件流输出的方式处理:
      //加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
      response.reset();//可以加也可以不加
      response.setContentType("application/x-download");
      String filedownload = "D:/primeton5/jakarta-tomcat-5.0.28/upload/2348.txt";
      String filedisplay = "2348.txt";
      filedisplay = URLEncoder.encode(filedisplay,"UTF-8");
      response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
      OutputStream outp = null;
      FileInputStream in = null;
      try
      {
          outp = response.getOutputStream();
          in = new FileInputStream(filedownload);
          byte[] b = new byte[1024];
          int i = 0;
          while((i = in.read(b)) > 0)
          {
              outp.write(b, 0, i);
          }
          outp.flush();
      }
      catch(Exception e)
      {
          System.out.println("Error!");
          e.printStackTrace();
      }
      finally
      {
          if(in != null)
          {
              in.close();
              in = null;
          }
          if(outp != null)
          {
              outp.close();
              outp = null;
          }
      }
%>

 

2.下载txt文件可以,但是文件内容中添加了文件名和文件的下载路径。下载jpg图片和word文件会显示乱码。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<% 
// 得到文件名字和路径 
String filename = "2312.jpg"; 
String filepath = "D:/primeton5/jakarta-tomcat-5.0.28/upload/"; 
// 设置响应头和下载保存的文件名 
response.setContentType("application/octet-stream"); 
response.setHeader("content-disposition", 
"attachment; filename=\"" + filename + "\""); 

// 打开指定文件的流信息 
java.io.FileInputStream fileinputstream = 
new java.io.FileInputStream(filepath + filename); 

// 写出流信息 
int i; 
while ((i=fileinputstream.read()) != -1) { 
out.write(i); 
} 
fileinputstream.close(); 
out.close(); 
%> 

 3.实际场景:应用从文件服务器下载文件。应用知道文件的URI.代码如下

@RequestMapping(value = "/resourcelibrary/downLoadResource.do")
public void downLoadResource(String name,String path,HttpServletRequest request,HttpServletResponse response) {
	         //path=path.replaceAll("/", "//");
	         HttpClient httpClient = new HttpClient();
	         // 创建GET方法的实例
	         GetMethod getMethod = new GetMethod(path); 
	         
	         BufferedInputStream bis = null;
	         BufferedOutputStream bos = null;
	         OutputStream fos = null;
	         InputStream fis = null;
	         
		try {
	         response.reset();
	         response.setHeader("Content-disposition",
	                 "attachment;success=true;filename ="
	                         + name);
	        
	         // 使用系统提供的默认的恢复策略sysInterface
             getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
	        //getMethod.setURI(new URI(url, charset));
	        
             // 执行getMethod
             int statusCode = httpClient.executeMethod(getMethod);
             
             fis=getMethod.getResponseBodyAsStream();
             bis = new BufferedInputStream(fis);
             fos = response.getOutputStream();
	         bos = new BufferedOutputStream(fos);
	         // 弹出下载对话框
	         int bytesRead = 0;
	         byte[] buffer = new byte[8192];
	         while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
	             bos.write(buffer, 0, bytesRead);
	         }
	         bos.flush();
	         fis.close();
	         bis.close();
	         fos.close();
	         bos.close();
	         } catch (HttpException e) {
	             // 发生致命的异常,可能是协议不对或者返回的内容有问题
	             System.out.println("Please check your provided http address!");
	             e.printStackTrace();
	         } catch (IOException e) {
	             // 发生网络异常
	             e.printStackTrace();
	         } finally {
	             // 释放连接 	 
	             getMethod.releaseConnection();
	             
            	try {
            		 if(fis!=null){
            			 fis.close();
            		 }
            		 if(bis!=null){
            			 bis.close();
            		 }
            		 if(fos!=null){
            			 fos.close();
            		 }
            		 if(bos!=null){
            			 bos.close();
            		 }
				} catch (IOException e) {
					e.printStackTrace();
				}
	             
	         }       
	    
	}

 总结:java.io.File读取文件,例如File file=new File(path)。path是本地服务器的路径的绝对路径,则没有问题,能读到指定文件。如果是URI的话,会报出找不到文件。其中会报java的斜杠转义的事情。如果把URL转换为URI呢,例如 URL url=new URL(path);File file=new File(url.toURI());这个时候会报出找不到file protocal的错误。

从URL读取指定文件使用File读取真的很难做到,可能有办法,但是我尝试了上面的2中方法都没有成功。后来,想到用httpClient读取跨域的URL文件,这样写入输出流就能下载到文件,真的做到了。httpClient的getMethod用完后,释放连接。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值