java文件下载

[b][color=red][size=medium]文件下载有两种方法:[/size][/color][/b]
1.直接在网站上放个链接地址,右键另存为,(文件名为中文时下载报错)
2.通过后台实现下载(代码实现 控制中文不乱码)

文件下载代码:

//其中%20是空格在UTF-8下的编码  
public String downloadLocal() throws FileNotFoundException, UnsupportedEncodingException {
HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
// 下载本地文件
String fileName = URLEncoder.encode("6767.pdf", "UTF-8"); // 文件的默认保存名
//fileName = fileName.replace("+", "%20");
File file = new File(getPath()+"/upload/ytytry5中文.pdf");
// 读到流中
InputStream inStream = new FileInputStream(getPath()+"/upload/gjw_123456_touzi.pdf");// 文件的存放路径
// 设置输出的格式
response.reset();
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return SUCCESS;
}


[size=large][i][color=blue][u]response.setContentType 参数参照[/u][/color][/i][/size][url]http://360193550.iteye.com/blog/2002915[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值