开发当中文件上传和下载是必不可少的两个常用接口,基于TP5的接口如下:
注意点:移动文件是需要绝对路径,访问文件时需要相对路径
单文件file格式上传
/**
*单文件上传
*[file] file 上传文件的字段
*[string] folder 文件保存的子级文件夹
**/
public function SingleUpload(){
// 获取表单上传文件
$files = request()->file('file');
if (!is_object($files)) {
CommonFunc::api_error("20000", "参数错误");
}
$category = pathinfo($files->getInfo('name'), PATHINFO_EXTENSION);
$dir_public = 'uploads/'.input('post.folder')."/".$category.'/'.date('Y-m-d', time())."/";
if(!is_dir($dir_public)){
mkdir($dir_public,0777,true);
}
$dir_root = ROOT_PATH ."public" . DS . $dir_public;
$origin = sha1($files->getInfo('name'));
$info = $files->move($dir_root , $origin);
if($info){
$path = "/".$dir_public . $origin .".". $info->getExtension();
}else{
return CommonFunc::api_error("20000" , "操作失败");
}
CommonFunc::api_export($path);
多文件file[]数组格式上传
/**
*多文件上传
*[array] file[] 上传文件的字段,注意:数组形式
*[string] folder 文件保存的子级文件夹
**/
public function MultiUpload(){
// 获取表单上传文件[]
$files = request()->file('file');
if (!is_array($files)) {
CommonFunc::api_error("20000", "参数错误");
}
foreach ($files as $value) {
$category = pathinfo($value->getInfo('name'), PATHINFO_EXTENSION);
$dir_public = 'uploads/'.input('post.folder')."/".$category.'/'.date('Y-m-d', time())."/";
if(!is_dir($dir_public)){
mkdir($dir_public,0777,true);
}
$dir_root = ROOT_PATH ."public" . DS . $dir_public;
$origin = sha1($value->getInfo('name'));
$info = $value->move($dir_root , $origin);
if($info){
$path[] = "/".$dir_public . $origin .".". $info->getExtension();
}else{
return CommonFunc::api_error("20000" , "操作失败");
}
}
$path = implode(',', $path);
CommonFunc::api_export($path);
}
图片以base64格式上传
public function fileUpload()
{
// 获取图片的base64编码
$base64_img = trim($this->post['img']);
//图片路径
$dir_public = "uploads/images/" . date('Y-m-d', time()) . "/";
$dir_root = ROOT_PATH . "public" . DS . $dir_public;
if(!file_exists($dir_root))
{
mkdir($dir_root);
}
if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result))
{
$type = $result[2];
if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
$origin = sha1((microtime(true) + rand(1, 10000)) . $this->admin['uid']);
$new_file = $dir_root. $origin. '.' .$type;
if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
$img_path = "/" . $dir_public . $origin . "." . $type;
}else{
CommonFunc::api_error("20000" , "图片上传失败!");
}
}else{
//文件类型错误
CommonFunc::api_error("20000" , "文件类型错误!");
}
}else{
//文件错误
CommonFunc::api_error("20000" , "文件错误!");
}
$path = array($img_path);
CommonFunc::api_export([
"list" => $path
]);
}
网友评论