java写response实现文件下载


import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;



public abstract class FileService {

	/**
	 *  filename 下载到客户端后的文件名称
	      *  file 待下载的文件
	 *	下载 文件
	 */
	public void downloadFileToClient(String filename,  File file, HttpServletResponse response) {

		FileInputStream inStream = null;
		try {
			inStream = new FileInputStream(file);
			byte[] buf = new byte[4096];
			int readLength;
			setResponseHeader(response, filename);
			while (((readLength = inStream.read(buf)) != -1)) {
				response.getOutputStream().write(buf, 0, readLength);
			}
		}catch (Exception e){
		}finally {
			try {
				inStream.close();
			} catch (Exception e) {

			}
		}
	}

	/**
	 *  设置响应头
	 * @param response
	 * @param fileName 文件名称
	 */
	protected void setResponseHeader(HttpServletResponse response, String fileName) {
		String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		String prefix = fileName.substring(0, fileName.lastIndexOf("."));
		try {
			response.reset();
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(prefix.getBytes("GB2312"), "8859_1")
					+ suffix);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	protected void downloadNetFile(String source, String dest) {
		// 下载网络文件
//		int bytesum = 0;
		int byteread = 0;
		InputStream inStream = null;
		FileOutputStream fs = null;
		try {
			URL url = new URL(source);

			URLConnection conn = url.openConnection();
			inStream = conn.getInputStream();
			fs = new FileOutputStream(dest);
			byte[] buffer = new byte[inStream.available()];
//			int length;
			while ((byteread = inStream.read(buffer)) != -1) {
//				bytesum += byteread;
				fs.write(buffer, 0, byteread);
			}
		} catch (Exception e) {
		} finally {
			if (null != inStream) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != fs) {
				try {
					fs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值