java 下载 文件名乱码_java下载文件文件名针对不同浏览器乱码,文件名中存在括号等乱码问题...

@Get("/downLoadDemoFile1")

public String downLoadDemoFile1(Invocation inv) {

String userAgent = inv.getRequest().getHeader("User-Agent");

String filename1 = "操作说明.pdf";

//针对IE或者以IE为内核的浏览器:

if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {

try {

filename1 = URLEncoder.encode(filename1, "UTF-8");

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} else {

//非IE浏览器的处理:

try {

filename1 = new String(filename1.getBytes("UTF-8"),"ISO-8859-1");

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

String filename = "dgsx.pdf";

String path = Constants.DOWNLOAD_BASE_FOLD+"/demo/"+filename;

logger.info(path);

InputStream ins = null;

BufferedInputStream bins = null;

OutputStream outs = null;

BufferedOutputStream bouts = null;

try {

path = new String(path.getBytes("ISO-8859-1"), "UTF-8");

File file = new File(path);// 构造要下载的文件

if (file.exists()) {

// String suffix = path.substring(path.lastIndexOf(".") + 1);

ins = new FileInputStream(path);// 构造一个读取文件的IO流对象

bins = new BufferedInputStream(ins);// 放到缓冲流里面

outs = inv.getResponse().getOutputStream();// 获取文件输出IO流

bouts = new BufferedOutputStream(outs);

inv.getResponse().setContentType("application/octet-stream;charset=utf-8");// 设置response内容的类型

// inv.getResponse().setHeader("Content-disposition","attachment;filename=\"" + URLEncoder.encode("操作说明.pdf", "UTF-8")+"\"");// 设置头部信息

inv.getResponse().setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename1));

// inv.getResponse().setContentType("application/vnd.ms-excel;charset=utf-8");

inv.getResponse().setCharacterEncoding("UTF-8");

int bytesRead = 0;

byte[] buffer = new byte[8192];

// 开始向网络传输文件流

while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {

bouts.write(buffer, 0, bytesRead);

}

bouts.flush();// 这里一定要调用flush()方法

} else {

logger.info("==============>>下载的文件不存在");

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (ins != null) {

ins.close();

ins = null;

}

if (bins != null) {

bins.close();

bins = null;

}

if (outs != null) {

outs.close();

outs = null;

}

if (bouts != null) {

bouts.close();

bouts = null;

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return "@";

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值