Home >php教程 >php手册 >浏览器打开页面实现文件下载的程序代码(php/jsp/java)

浏览器打开页面实现文件下载的程序代码(php/jsp/java)

WBOY
WBOYOriginal
2016-06-13 10:01:281497browse

浏览器打开页面实现文件下载的程序代码(php/jsp/java) 有需要学习的同学可参考一下。

tomcat中配置如下:

 代码如下 复制代码

   
        txt
        application/octet-stream
   

   
        jpg
        application/octet-stream
   

对于如上配置,当访问扩展名txt或jpg的资源时就出现下载提示框,如果只需要对某些提到的资源让其出现下载提示框,上述配置就不行了,解决的方法是在资源的response头中设置content-type即可,例如:

php 中

 代码如下 复制代码

header("Content-type:application/octet-stream");
header('Content-Disposition: attachment; filename="downloaded.txt"');

下载文件程序

 代码如下 复制代码

header("content-type:text/html; charset=utf-8");
$file_name=$_GET['name']; //服务器的真实文件名
$file_realName=urldecode($_GET['real']); //数据库的文件名urlencode编码过的
$file_dir="upload/";
$file = fopen($file_dir . $file_name,"r"); // 打开文件
// 输入文件标签
header( "Pragma: public" );
header( "Expires: 0" );
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir . $file_name));
Header("Content-Disposition: attachment; filename=" . iconv("UTF-8","GB2312//TRANSLIT",$file_realName));
// 输出文件内容
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit;
?>


java 中

 代码如下 复制代码
response.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment;filename="downloaded.txt");

如果需要为下载设置一个保存的名字,可以用Content-Disposition属性来指定。

实例

 代码如下 复制代码

  response.reset();//可以加也可以不加
  response.setContentType("application/x-download");//设置为下载application/x-download
  // /../../退WEB-INF/classes两级到应用的根目录下去,注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/
  ServletContext context = session.getServletContext();
  String realContextPath = context.getRealPath("")+"\plan\计划数据模板.xls";
  String filenamedisplay = "计划数据模板.xls";
  filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
  response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
  OutputStream output = null;
  FileInputStream fis = null;
  try
  {
  output  = response.getOutputStream();
  fis = new FileInputStream(realContextPath);
  byte[] b = new byte[1024];
  int i = 0;
  while((i = fis.read(b)) > 0)
  {
  output.write(b, 0, i);
  }
  output.flush();
  }
  catch(Exception e)
  {
  System.out.println("Error!");
  e.printStackTrace();
  }
  finally
  {
  if(fis != null)
  {
  fis.close();
  fis = null;
  }
  if(output != null)
  {
  output.close();
  output = null;
  }
  }
  %>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn