文件下载实现专栏

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改变即可。

你可能感兴趣的:(JavaScript,iframe,header,File,download,web服务)