ThinkPHP6 公共 上传到本地
发布时间:2022-07-29, 11:20:31 分类:PHP | 编辑 off 网址 | 辅助
图集1/1
正文 4788字数 379,295阅读
<?php
namespace app\common\lib\files;
use think\Exception;
use think\exception\ValidateException;
class upload
{
private $domain;
protected $name;
protected $type;
protected $module;
protected $image;
public function __construct($name = '',$type = 'image',$image = [])
{
$this->name = $name;
$this->type = $this->checkUpload($type);
$this->module = request()->app_name();
$this->image = $image;
$this->domain = Request()->domain();
}
protected $config = [
'image' => [
'validate' => [
'size' => 10*1024*1024,
'ext' => 'jpg,png,gif,jpeg',
],
'path' => '/images',
],
'audio' => [
'validate' => [
'size' => 100*1024*1024,
'ext' => 'mp3,wav,cd,ogg,wma,asf,rm,real,ape,midi',
],
'path' => '/audios',
],
'video' => [
'validate' => [
'size' => 100*1024*1024,
'ext' => 'mp4,avi,rmvb,rm,mpg,mpeg,wmv,mkv,flv',
],
'path' => '/videos',
],
'file' => [
'validate' => [
'size' => 5*1024*1024,
'ext' => 'doc,docx,xls,xlsx,pdf,ppt,txt,rar,zip,pem,p12',
],
'path' => '/files',
],
];
private function checkUpload($type){
try{
if(empty($_FILES) || empty($_FILES[$this->name])) throw new Exception("未上传文件!");
if(!in_array($type,array_keys($this->config))) throw new Exception("文件类型不存在!");
return $type;
}catch (Exception $e){
return \app\common\controller\Base::show(100,$e->getMessage());
}
}
public function upfile($infoSwitch = false){
$file = request()->file($this->name);
try{
if($file == null) throw new ValidateException("the file cannot be empty");
validate(['file' => self::validateFile()])->check(['file' => $file]);
$savename = \think\facade\Filesystem::disk('public')->putFile( $this->module.$this->config[$this->type]['path'], $file);
if($infoSwitch){
return self::getFileInfo($file,$savename);
}
return $savename;
}catch (\think\exception\ValidateException $e){
return \app\common\controller\Base::show(100,self::languageChange($e->getMessage()));
}
}
private function validateFile(){
if(empty($this->image)){
$validataType = [
'fileSize' => $this->config[$this->type]['validate']['size'],
'fileExt' => $this->config[$this->type]['validate']['ext'],
];
}else{
if(is_array($this->image)) throw new ValidateException("");
$validataType = [
'fileSize' => $this->config[$this->type]['validate']['size'],
'fileExt' => $this->config[$this->type]['validate']['ext'],
'image' => $this->image //示例值 [200,200]
];
}
return $validataType;
}
private function languageChange($msg){
$data = [
'the file cannot be empty' => '文件不能为空!',
'unknown upload error' => '未知上传错误!',
'file write error' => '文件写入失败!',
'upload temp dir not found' => '找不到临时文件夹!',
'no file to uploaded' => '没有文件被上传!',
'only the portion of file is uploaded' => '文件只有部分被上传!',
'upload File size exceeds the maximum value' => '上传文件大小超过了最大值!',
'upload write error' => '文件上传保存错误!',
];
return $data[$msg] ?? $msg;
}
private function getFileInfo($file,$savename){
$info = [
'path' => config('filesystem.disks.public.url').'/'.str_replace('\\','/',$savename),
'url' => $this->domain.config('filesystem.disks.public.url').'/'.str_replace('\\','/',$savename),
'size' => $file->getSize(),
'name' => $file->getOriginalName(),
'mime' => $file->getMime(),
'ext' => $file->extension()
];
return $info;
}
}
Run code
Cut to clipboard
小破孩博客
(支付宝)给作者钱财以资鼓励 (微信)→
有过 4 条评论 »
<?php /** *公共文件上传 * User: Hm * Date: 2020/9/16 * Email: <2938039696@qq.com> **/ declare (strict_types = 1); namespace app\union\controller; use think\exception\ValidateException; class Upload extends Base { /* * 单文件上传 * */ public function uploadImg(){ //判断是否是POST请求,如果是处理上传逻辑 if (request()->isPost()){ //接收文件上传目录 $namePath = request()->param('type'); //获取表单上传文件 $file = request()->file('file'); $upload_dir = '/'.$namePath; //组装文件保存目录 $suffix='jpg,jpeg,png,gif'; //文件格式 $size='3'; //文件大小 try { //验证器验证上传的文件 validate(['file'=>[ //限制文件大小 'fileSize' => $size * 1024 * 1024, //限制文件后缀 'fileExt' => 'jpg,jpeg,png,gif' ]],[ 'file.fileSize' => '上传的文件大小不能超过'.$size.'M', 'file.fileExt' => '请上传后缀为:'.$suffix.'的文件' ])->check(['file'=>$file]); //上传文件到本地服务器 $filename = \think\facade\Filesystem::disk('public')->putFile($upload_dir, $file); ; if ($filename){ $src = '/uploads/'.str_replace('\\', '/', $filename); return json(['code'=>1,'msg'=>'上传成功','data'=>['src'=>$src]]); }else{ return json(['code'=>0,'msg'=>'上传失败']); } }catch (ValidateException $e){ return json(['code'=>0,'msg'=>$e->getMessage()]); } }else{ return json(['code'=>0,'msg'=>'非法请求']); } } } ?>
打印一下上传的文件对象可以的得出,大致对象结构如下 object(thinkFile)#77 (13) { ["error":"thinkFile":private] => string(0) "" ["filename":protected] => string(14) "/tmp/phpkIAvIy" ["saveName":protected] => NULL ["rule":protected] => string(4) "date" ["validate":protected] => array(0) { } ["isTest":protected] => NULL ["info":protected] => array(5) { ["name"] => string(10) "ebrima.ttf" ["type"] => string(24) "application/octet-stream" ["tmp_name"] => string(14) "/tmp/phpkIAvIy" ["error"] => int(0) ["size"] => int(907232) } ["hash":protected] => array(0) { } ["pathName":"SplFileInfo":private] => string(14) "/tmp/phpkIAvIy" ["fileName":"SplFileInfo":private] => string(9) "phpkIAvIy" ["openMode":"SplFileObject":private] => string(1) "r" ["delimiter":"SplFileObject":private] => string(1) "," ["enclosure":"SplFileObject":private] => string(1) """ } 看这结构,访问权限是protected,如何获取呢? 获取方法: 对象->getInfo() 获取info属性 //对象->getInfo() 获取info属性,['name'] 获取name的值 $file->getInfo()['name']
HTML5 input file类型,accept(文件类型控制)
accept的文件类型
accept表示可以上传文件类型,image表示图片,*表示所有支持的格式。 只支持excel文件类型上传 <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" multiple="multiplt"> *表示所有支持的格式 <input type="file" accept="*" multiple="multiplt" /> 支持所有的图像(图片)文件 <input type="file" accept="image/*" multiple="multiplt" /> 上传Pdf <input type="file" accept="application/msword, application/pdf" multiple="multiplt" /> 上传 .zip,.rar <input type="file" accept=".zip,.rar,application/x-rar-compressed,application/zip,application/x-zip-compressed,application/octet-stream" multiple="multiplt"/>
accept="image/gif, image/jpeg" accept="application/msword" accept="application/pdf" accept="application/poscript" accept="application/rtf" accept="application/x-zip-compressed" accept="audio/basic" accept="audio/x-aiff" accept="audio/x-mpeg"
public function download() { $famlePath = $_GET['resum']; $file_dir = ROOT_PATH . 'public' . DS . 'uploads' . '/' . "$famlePath"; // 下载文件存放目录 // 检查文件是否存在 if (! file_exists($file_dir) ) { $this->error('文件未找到'); }else{ // 打开文件 $file1 = fopen($file_dir, "r"); // 输入文件标签 Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length:".filesize($file_dir)); Header("Content-Disposition: attachment;filename=" . $file_dir); ob_clean(); // 重点!!! flush(); // 重点!!!!可以清除文件中多余的路径名以及解决乱码的问题: //输出文件内容 //读取文件内容并直接输出到浏览器 echo fread($file1, filesize($file_dir)); fclose($file1); exit(); } }
{$product.desc|raw}