浏览器打开页面实现文件下载的程序代码(php/jsp/java)
浏览器打开页面实现文件下载的程序代码(php/jsp/java) 有需要学习的同学可参考一下。
tomcat中配置如下:
代码如下 | 复制代码 |
|
对于如上配置,当访问扩展名txt或jpg的资源时就出现下载提示框,如果只需要对某些提到的资源让其出现下载提示框,上述配置就不行了,解决的方法是在资源的response头中设置content-type即可,例如:
php 中
代码如下 | 复制代码 |
header("Content-type:application/octet-stream"); |
下载文件程序
代码如下 | 复制代码 |
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();//可以加也可以不加 |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
