文件下载实现专栏

1.一般直接请求(window.location之类的方法)的话,会弹出空白页面,避免空白页面的方法:

<!-- 把下面代码加到<body>区域中 -->
<IFRAME src="http://localhost/img/test.rar" frameborder=0 scrolling=no vspace=0 hspace=0 marginheight=0 marginwidth=0 height=0 width=0>
</IFRAME>

这个是一个不会显示出来的IFRAME,每次请求只要改变src属性的值就可以了。

 

2 .header Content-Disposition参数说明

Content-Disposition参数:
attachment — 作为附件下载    
inline — 在线打开
具体使用如:header (”Content-Disposition : inline; filename=文件名.mp3″);

需要注意以下几个问题:
Content-disposition是MIME协议的扩展,由于多方面的安全性考虑没有被标准化,所以可能某些浏览器不支持,比如说IE4.01

我们可以使用程序来使用它,也可以在web服务器(比如IIS)上使用它,只需要在http header上做相应的设置即可

在JAVA中 :response.setHeader("Content-disposition","attachment;filename=xxx.rar");

其中Content-disposition后面的值,filename表示的是在下载框中显示的文件名;

 

3.下载文件的代码 :(选自http://zhangjunhd.blog.51cto.com/113473/19631

package com.zj.sample;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class LoadFile extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws IOException, ServletException {
       OutputStream o = response.getOutputStream();
       byte b[] = new byte [1024];
       // the file to download.
       File fileLoad = new File( "d:/temp" , "test.rar" );
       // the dialogbox of download file.
       response.setHeader( "Content-disposition" , "attachment;filename=" + "test.rar" );
       // set the MIME type.
       response.setContentType( "application/x-tar" );
       // get the file length.
       long fileLength = fileLoad.length();
       String length = String.valueOf (fileLength);
       response.setHeader( "Content_Length" , length);
       // download the file.
       FileInputStream in = new FileInputStream(fileLoad);
       int n = 0;
       while ((n = in.read(b)) != -1) {
           o.write(b, 0, n);
       }
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
       doGet(request, response);
    }
}


只想说一点 :上面的代码是服务器响应下载请求的代码,代码可以优化,过程不需要再经过特殊处理。最后只要在IFRAME的src中将请求url写进去,3中的代码可以响应即可。记住,想动态转换,请求不同的资源,只需要用JavaScript将IFRAME的src改变即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值