从服务器下载文件

1、下载的servlet DownloadServlet.java

package cn.demo.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.demo.utils.DownUtils;

public class DownloadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		// 设置要下载的文件路径
		String realPath = this.getServletContext().getRealPath("/WEB-INF/kk/郁金香.jpg");
		File file = new File(realPath);
		if (!file.exists()) {
			throw new RuntimeException("文件已经被删除");
		}

		String filename = file.getName();
		System.out.println("filename: " + filename);

		// 处理下载文件名中文乱码问题
		filename = DownUtils.getAttachmentFilement(filename, request.getHeader("user-agent"));

		// 设置浏览器下载弹框
		response.setHeader("Content-Disposition", "attachment;filename=" + filename);

		// 告知浏览器下载文件的mime类型
		String mime = this.getServletContext().getMimeType(filename);
		response.setContentType(mime);

		// 以流的形式发送给浏览器
		ServletOutputStream out = response.getOutputStream();

		// 读取服务器文件
		InputStream in = new FileInputStream(file);
		int len = 0;
		byte[] bytes = new byte[4 * 1024];// 每次读取4M
		while ((len = in.read(bytes)) != -1) {
			out.write(bytes, 0, len);// 写入
		}
		// 关闭输入流
		in.close();
	}

}

2、DownUtils

	public static String getAttachmentFilement(String filename, String header)
			throws UnsupportedEncodingException {

		if (header.contains("Firefox")) {// 火狐浏览器
			filename = "=?utf-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?=";
		} else {
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}

转载于:https://my.oschina.net/bob1900/blog/807917

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值