search

THinkPHP中文件下载

 THinkPHP1.5中文件的下载 用到的系统类库文件是Http.class.php,位于ThinkPHP\Lib\ORG\Net目录下,类名Http,其中有静态方法static function download ($filename, $showname=”,$content=”,$expire=180);/     @param string $filename 下载文件名(完整路径加文件的保存名字)* @param string $showname 下载显示的文件名(想要显示的名字或者从数据库中读出的原来带中文的名字);* @param string $content  下载的内容(默认为空,此时下载的文件就是原文件)。* @param integer $expire  下载内容浏览器缓存时间 ,默认为空时为180秒。*/因为PHP保存文件名不支持中文,所以通常中文文件名保存到服务器上时换成成英文名或者生成随机名字。下载时可以利用此方法回复原文件名。应用举例:下载时显示文件原名/* 假设数据库里文件信息存储表为file(id,truename,savenane,user,size).文件存在于网站项目目录下的uploads文件夹里,本网站项目名为bm,其绝对路径为:H:\AppServ\www\bm\uploads\(  H:\AppServ\www\为文档根目录)此时该目录下有一文件123456789.doc,(savename),原文件名为“读后感.doc”,即truename,大小为2MB.那么要下载时服务器端得程序为:class FileAction extends Action{public function download(){$uploadpath=’H:\AppServ\www\bm\uploads\’;//设置文件上传路径,服务器上的绝对路径$id=$_GET['id'];//GET方式传到此方法中的参数id,即文件在数据库里的保存id.根据之查找文件信息。if($id==”) //如果id为空而出错时,程序跳转到项目的Index/index页面。或可做其他处理。{$this->redirect(‘index’,'Index’,”,APP_NAME,”,1);}$file=D(‘File’);//利用与表file对应的数据模型类FileModel来建立数据对象。$result= $file->find($id);//根据id查询到文件信息if($result==false) //如果查询不到文件信息而出错时,程序跳转到项目的Index/index页面。或可做其他处理{$this->redirect(‘index’,'Index’,”,APP_NAME,”,1);}$savename=$file->savename;//文件保存名$showname=$file->truename;//文件原名$filename=$uploadpath.$savename;//完整文件名(路径加名字)import(‘ORG.Net.Http’);Http::download($filename,$showname);}}然后在该文件下载的HTML模板里要下载该文件的地方加一个下载链接,调用File模块的download方法即可。记得传参数id .如本例中:<table><tr><td>读后感.doc</td><td>sunmoon</td><td><a href=’__APP__/File/download/id/{$id}’>下载</a></td><!–其中{$id}是模板变量,代表要下载的文件在数据库中的保存id.–></tr></table> 注:IE浏览器的下载文件名编码只有gb2312才能显示,若是不然,要不就是文件名乱码,要不就是找不到文件而无法下载。针对此种情况,我对原来的download()方法进行了一些调整,经过测试发现IE、傲游、firefox均可正常下载。    /**     +----------------------     * 下载文件     * 可以指定下载显示的文件名,并自动发送相应的Header信息     * 如果指定了content参数,则下载该参数的内容     +----------------------     * @static     * @access public     +----------------------     * @param string $filename 下载文件名     * @param string $showname 下载显示的文件名     * @param string $content  下载的内容     * @param integer $expire  下载内容浏览器缓存时间     +----------------------     * @return void     +----------------------     * @throws ThinkExecption     +----------------------     */    static public function download ($filename, $showname='',$content='',$expire=180) {  if(file_exists($filename)){   $length = filesize($filename);  }elseif(is_file(UPLOAD_PATH.$filename)){   $filename = UPLOAD_PATH.$filename;   $length = filesize($filename);  }elseif($content != ''){   $length = strlen($content);   }else {   throw_exception($filename.L('下载文件不存在!'));  }  if(empty($showname)){   $showname = $filename;  }  $showname = basename($showname);  if(empty($filename)){   $type = mime_content_type($filename);  }else{   $type = "application/octet-stream";  }  //发送Http Header信息 开始下载  header("content-type:text/html; charset=utf-8");  header("Pragma: public");  header("Cache-control: max-age=".$expire);  //header('Cache-Control: no-store, no-cache, must-revalidate');  header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");  header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");  //下面一行就是改动的地方,即用iconv("UTF-8","GB2312//TRANSLIT",$showname)系统函数转换编码为gb2312  header("Content-Disposition: attachment; filename=". iconv("UTF-8","GB2312",$showname)); header("Content-Length: ".$length);  header("Content-type: ".$type);  header('Content-Encoding: none');  header("Content-Transfer-Encoding: binary" );  if($content == '' ) {   readfile($filename);  }  else { echo($content); }  exit();      }注:iconv为php系统函数库,但需要安装。若是服务器还没有这个模块安装,则需将iconv.dll下载下来后复制到windows/system32/下面,同时在php安装文件夹得ext文件夹里也复制一份。然后在php.ini文件中将extension=php_iconv.dll前的”;”去掉,没有的话就加上extension=php_iconv.dll。然后重启服务器即可。

?

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

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.