Servlet实现文件下载

2 篇文章 0 订阅

第一次使用servlet下载,写个demo留着以后参考.代码如下:

public Result downloadFile(HttpServletRequest request,
HttpServletResponse response) {
String target = request.getParameter("target");
File file = new File(FileUtil.MeeStorage + target);
if (!file.exists())
return null;
if (file.exists()) {
try {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("GB2312");
String fname = new String(file.getName().getBytes("GBK"),"ISO8859-1");//防止中文乱码
doDownload(request, response, file);
} catch (Exception e) {
e.printStackTrace();
}
}
return new Result(Type.download, null, "/WEB-INF/fileIndex.jsp", true);
}


private void doDownload(HttpServletRequest req, HttpServletResponse resp,
File file) throws IOException {
int length = 0;
ServletOutputStream op = resp.getOutputStream();
ServletContext context = (ServletContext)req.getAttribute("ServletContext");//serlet中的getServletConfig().getServletContext(),这里封装了一下
String mimetype = context.getMimeType(file.getPath());


resp.setContentType((mimetype != null) ? mimetype
: "application/octet-stream");
resp.setContentLength((int) file.length());
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ file.getName() + "\"");


byte[] buffer = new byte[4096];
DataInputStream in = new DataInputStream(new FileInputStream(file));


while ((in != null) && ((length = in.read(buffer)) != -1)) {
op.write(buffer, 0, length);
}
in.close();
op.flush();
op.close();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值