Browse Source

Keep the source file name when downloading the attachment/下载附件的时候保持源文件名字

star7th 4 years ago
parent
commit
f772d60dc7

+ 4 - 0
server/Application/Api/Controller/AdminUserController.class.php

@@ -78,6 +78,10 @@ class AdminUserController extends BaseController {
         $password = I("password");
         $uid = I("uid");
         $name = I("name");
+        if(!$username){
+            $this->sendError(10101,'用户名不允许为空');
+            return ;
+        }
         if($uid){
             if($password){
                 D("User")->updatePwd($uid, $password);

+ 49 - 1
server/Application/Api/Controller/AttachmentController.class.php

@@ -43,7 +43,14 @@ class AttachmentController extends BaseController {
                 $url = $ret['real_url']  ;
             }
 
-        header("location:{$url}");
+        $array = explode("/Public/Uploads/", $url) ;
+        $file_path = "../Public/Uploads/".$array[1] ;
+		if (file_exists($file_path) && $ret['display_name']) {
+            $this->_downloadFile($file_path, $ret['display_name']);
+		}else{
+            header("location:{$url}");
+        }
+        
       }else{
         echo "www.showdoc.cc";
       }
@@ -341,4 +348,45 @@ class AttachmentController extends BaseController {
 
     }
 
+    //输出本地文件到浏览器
+    public function _downloadFile($filename, $rename='showdoc') {
+
+    
+        //设置脚本的最大执行时间,设置为0则无时间限制
+        set_time_limit(3000);
+        ini_set('max_execution_time', '0');
+    
+        //通过header()发送头信息
+        //因为不知道文件是什么类型的,告诉浏览器输出的是字节流
+        header('content-type:application/octet-stream');
+    
+        //告诉浏览器返回的文件大小类型是字节
+        header('Accept-Ranges:bytes');
+    
+        //获得文件大小
+        $filesize = filesize($filename);//(此方法无法获取到远程文件大小),远程文件用下面get_headers方法
+        //$header_array = get_headers($filename, true);
+        //$filesize = $header_array['Content-Length'];
+        //var_dump($header_array);exit();
+        //告诉浏览器返回的文件大小
+        header('Accept-Length:'.$filesize);
+        //告诉浏览器文件作为附件处理并且设定最终下载完成的文件名称
+        header('content-disposition:attachment;filename='.basename($rename));
+    
+        //针对大文件,规定每次读取文件的字节数为4096字节,直接输出数据
+        $read_buffer = 4096;
+        $handle = fopen($filename, 'rb');
+        //总的缓冲的字节数
+        $sum_buffer = 0;
+        //只要没到文件尾,就一直读取
+        while(!feof($handle) && $sum_buffer<$filesize) {
+            echo fread($handle,$read_buffer);
+            $sum_buffer += $read_buffer;
+        }
+    
+        //关闭句柄
+        fclose($handle);
+
+    }
+
 }