java文件下载设置中文名称的实例(response.addHeader)
程序员文章站
2024-02-25 15:30:09
实例如下:
protected void dopost(httpservletrequest request, httpservletresponse respo...
实例如下:
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string browser = ""; string filename = "测试.txt"; try { browser = request.getheader("user-agent"); if (-1 < browser.indexof("msie 6.0") || -1 < browser.indexof("msie 7.0")) { // ie6, ie7 浏览器 response.addheader("content-disposition", "attachment;filename=" + new string(filename.getbytes(), "iso8859-1")); } else if (-1 < browser.indexof("msie 8.0")) { // ie8 response.addheader("content-disposition", "attachment;filename=" + urlencoder.encode(filename, "utf-8")); } else if (-1 < browser.indexof("msie 9.0")) { // ie9 response.addheader("content-disposition", "attachment;filename=" + urlencoder.encode(filename, "utf-8")); } else if (-1 < browser.indexof("chrome")) { // 谷歌 response.addheader("content-disposition", "attachment;filename*=utf-8''" + urlencoder.encode(filename, "utf-8")); } else if (-1 < browser.indexof("safari")) { // 苹果 response.addheader("content-disposition", "attachment;filename=" + new string(filename.getbytes(), "iso8859-1")); } else { // 火狐或者其他的浏览器 response.addheader("content-disposition", "attachment;filename*=utf-8''" + urlencoder.encode(filename, "utf-8")); } } catch (exception e) { e.printstacktrace(); } inputstream in = new fileinputstream("d:\\test.txt");//获取文件输入流 int len = 0; byte[] buffer = new byte[1024]; outputstream out = response.getoutputstream(); while ((len = in.read(buffer)) > 0) { out.write(buffer,0,len);//将缓冲区的数据输出到客户端浏览器 } in.close(); out.flush(); out.close(); }
判断各个浏览器,然后进行解码和加码。
以上这篇java文件下载设置中文名称的实例(response.addheader)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。