下载文件,文件名包含中文特殊符号的处理,不同浏览器

此博客展示了一段Java代码,用于实现附件下载功能。代码接收请求中的文件名和文件路径,根据不同浏览器对文件名进行编码处理,若文件存在则将其以二进制流形式输出到响应中,最后关闭输入输出流,若文件不存在则给出提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**

* 下载附件

* @param mapping

* @param form

* @param request

* @param response

* @throws Exception

*/

public void download(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

String filename = request.getParameter("filename");

 

String filepath = request.getParameter("filepath");

log.info("一开始的filepath:"+filepath);

 

String realPath = request.getSession().getServletContext()

.getRealPath("").replace("\\", "/");

BufferedInputStream bis = null;

ServletOutputStream sos = null;

try{

File file = new File(filepath);

if(!file.exists()){

response.getWriter().write("<script language=javascript>alert('file does not exist!');history.back();</script>");

}else{

response.reset();

String sloadName=new String(filename.getBytes("gb2312"),"iso8859-1");

if (request.getHeader("User-Agent").toLowerCase()

.indexOf("firefox") > 0) {

sloadName = new String(filename.getBytes("gb2312"), "ISO8859-1"); // firefox浏览器

log.info("firefox浏览器 ");

} else if (request.getHeader("User-Agent").toUpperCase()

.indexOf("CHROME") > 0) {

log.info("谷歌浏览器");

System.out.println("谷歌浏览器");

sloadName = new String(filename.getBytes("gb2312"), "ISO8859-1");// 谷歌

} else if (request.getHeader("User-Agent").toUpperCase()

.indexOf("MSIE") > 0) {

sloadName = URLEncoder.encode(filename, "UTF-8");// IE浏览器

}

System.out.println(sloadName);

response.setContentType("bin");

response.setHeader("Content-Disposition","attachment;filename=\""+sloadName+"\"");

bis = new BufferedInputStream(new FileInputStream(file));

byte[] buf = new byte[1024];

int len = 0;

sos = response.getOutputStream();

while ((len = bis.read(buf)) > 0){

sos.write(buf, 0, len);

}

sos.flush();

}

}catch(Exception e){

e.printStackTrace();

}finally{

if(bis!=null)

bis.close();

if(sos!=null)

sos.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值