123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- <?php
- declare(strict_types=1);
- namespace app\utils;
- use think\Response;
- use think\response\File;
- /**
- * 返回操作 utils
- *
- * @version 0.0.1
- * @author by huwhois
- * @time 20228/10
- */
- class ReUtils
- {
- /**
- * 操作成功的返回
- * @access protected
- * @param mixed $msg 提示信息
- * @param mixed $data 返回的数据
- * @param array $header 发送的Header信息
- * @return void
- */
- public static function success($msg = 'success', array $header = [])
- {
- $result = [
- 'code' => 0,
- 'msg' => $msg,
- ];
- return Response::create($result, 'json')->header($header);
- }
- /**
- * 操作成功的返回
- * @access protected
- * @param mixed $msg 提示信息
- * @param array $header 发送的Header信息
- * @return void
- */
- public static function error($msg = 'fail', $code = 1, string $type = '', array $header = [])
- {
- $result = [
- 'code' => $code,
- 'msg' => $msg,
- ];
- $type = $type ?: 'json';
- return Response::create($result, $type)->header($header);
- }
- /**
- * 返回封装后的API数据到客户端
- * @param mixed $data 要返回的数据
- * @param integer $code 返回的code
- * @param mixed $msg 提示信息
- * @param string $type 返回数据格式
- * @param array $header 发送的Header信息
- * @return Response
- */
- public static function result($data, int $code = 0, $msg = '', string $type = '', array $header = []): Response
- {
- $result = [
- 'code' => $code,
- 'msg' => $msg,
- 'data' => $data,
- ];
- $type = $type ?: 'json';
- return Response::create($result, $type)->header($header);
- }
- /**
- * 获取\think\response\Download对象实例
- * @param string $filename 要下载的文件
- * @param string $name 下载文件显示名
- * @return \think\response\File
- */
- public static function sendTempZip(string $filename, string $name = "")
- {
- $fp = fopen($filename, "r");
- $file_size = filesize($filename); //获取文件的字节
- $name = $name ?: basename($filename);
- // halt($file_size);
- //下载文件需要用到的头
- Header("Content-type: application/zip");
- Header("Accept-Ranges: bytes");
- Header("Accept-Length:" . $file_size);
- Header("Content-Disposition: attachment; filename=$name");
- $buffer = 1024 * 4; //设置一次读取的字节数,每读一取次,就输出数据(即返回给浏览器)
- $file_count = 0; //读取的总字节数
- //向浏览器返回数据 如果下载完成就停止输出,如果未下载完成就一直在输出。根据文件的字节大小判断是否下载完成
- while (!feof($fp) && $file_count < $file_size) {
- $file_con = fread($fp, $buffer);
- $file_count += $buffer;
- echo $file_con;
- }
- fclose($fp);
- // 下载完成后删除压缩包,临时文件夹
- if ($file_count >= $file_size) {
- unlink($filename);
- }
- }
- }
|