JAVA文件下载,页面显示另存为效果
2024-08-24 00:25:22
经过测试 firefox、QQ、IE 浏览器是可以的 chrome浏览器不行(直接下载了)
1. 系统框架springmvc+jsp
2. 后台servlet代码
@RequestMapping("download")
public void download(HttpServletRequest request,HttpServletResponse response){
BufferedInputStream dis = null;
BufferedOutputStream fos = null; String urlString = request.getParameter("urlString");
String fileName = urlString.substring(urlString.lastIndexOf('/') + 1); try { URL url = new URL(urlString);
//response.setContentType("application/x-msdownload;");
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength())); dis = new BufferedInputStream(url.openStream());
fos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
fos.write(buff, 0, bytesRead);
} } catch (Exception e) {
e.printStackTrace();
} finally {
if (dis != null)
try{
dis.close();
}catch (Exception e){
e.printStackTrace();
}
if (fos != null)
try{
fos.close();
}catch (Exception e){
e.printStackTrace();
} }
}
3. 页面jsp代码
<input type="button" onclick="downloadImage()" value="下载"> <script>
function downloadImage(){
var urlString = "http://pic32.nipic.com/20130829/12906030_124355855000_2.png";
//跳转到后端控制器
location.href="${ctx}/guest/download.do?urlString="+urlString;
}
</script>
4. 下载效果1(firefox)
下载效果2(QQ)
最新文章
- [Excel] WorkBook.SaveAs
- PXE网络启动提示no default or ui configuration directive问题解决
- Angularjs中文版本开发指南发布
- Where art thou
- 使用UIKit制作卡牌游戏(二)ios游戏篇
- TYVJ P1016 装箱问题 Label:01背包 DP
- 【WebForm】Js调用后台C#方法
- CUDA常见问题之无法在c文件中调用cu文件中定义的函数
- ASCII 码表对照
- 【POJ1707】【伯努利数】Sum of powers
- CString 与 std::string 相互转化
- pycharm+QT4的helloworld
- android音乐播放器开发 SweetMusicPlayer 智能负载直插式歌词
- 【转载】Spark运行架构
- spring cloud 微服务调用--ribbon和feign调用
- uva 10123 - No Tipping dp 记忆化搜索
- pickle详解
- 消息中间件系列五:RabbitMQ的使用场景(异步处理、应用解耦)
- spring cloud config服务器
- js 正则表达式,匹配邮箱/手机号/用户名
热门文章
- 66、多种多样的App主界面Tab(1)------ ViewPager实现Tab
- LNMP+Zabbix搭建
- 时间查询缺少部分数据 mvc 解决方案
- [LintCode] 二叉树的前序遍历
- XXE(xml外部实体注入漏洞)
- centos7.3下使用yum 安装pip
- extern的原理很简单,就是告诉编译器:“你现在编译的文件中,有一个标识符虽然没有在本文件中定义,但是它是在别的文件中定义的全局变量,你要放行!”
- 容灾 RPO RTO
- Spring 的IOC容器之注解的方式
- 服务不支持 chkconfig 的解决方法