Thinkphp上传图片至OSS

时间:2019-11-26
本文章向大家介绍Thinkphp上传图片至OSS,主要包括Thinkphp上传图片至OSS使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
/* OSS图片上传
* liwei
* */
public function oss_uploadImage()
{
$config['KeyId']='LTAIMyL4LeeBgTY5';
$config['KeySecret']='jkSN5ycNNPhrhbV0sQvLX61dllXbE7';
$config['Endpoint']='http://oss-cn-beijing.aliyuncs.com';
$config['Bucket']='hidden-danger';
if (request()->has('base64', 'post')) {
$data = $_POST['base64'];
$result = $this->new_base64_upload($data);
if ($result['status'] === 200) {
$fileResult = &$result['data'];
$filePath = $fileResult['path'] . $fileResult['name'];
$ossFileName = implode('/', ['upload/image', date('Ymd'), $fileResult['name']]);
try {
import('AliyunOss.autoload',EXTEND_PATH,'.php');
//实例化对象 将配置传入
$ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
$result = $ossClient->uploadFile($config['Bucket'], $ossFileName, $filePath);
$arr = [
'oss_url' => $result['info']['url'], //上传资源地址
'relative_path' => $ossFileName //数据库保存名称(相对路径)
];
} catch (OssException $e) {
return $e->getMessage();
} finally {
unlink($filePath);
}
$this->jsonReturn(0, '成功oss', array('file' => $arr['oss_url']));
}
return json(['status'=>0,'msg'=>$result['msg']]);
} else {
/*获取到上传的文件*/
//$file = request()->file('file');
$file = $_FILES['file'];
if ($file) {
$name = $file['name'];
$format = strrchr($name, '.');//截取文件后缀名如 (.jpg)
/*判断图片格式*/
$allow_type = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
if (!in_array($format, $allow_type)) {
return json(['status'=>0,'msg'=>"文件格式不在允许范围内哦"]);
}
// 尝试执行
try {
import('AliyunOss.autoload',EXTEND_PATH,'.php');
//实例化对象 将配置传入
$ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
//这里是有sha1加密 生成文件名 之后连接上后缀
$fileName = 'uplaod/image/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . $format;
//执行阿里云上传
$result = $ossClient->uploadFile($config['Bucket'], $fileName, $file['tmp_name']);
/*组合返回数据*/
$arr = [
'oss_url' => $result['info']['url'], //上传资源地址
'relative_path' => $fileName //数据库保存名称(相对路径)
];
} catch (OssException $e) {
return $e->getMessage();
}
//将结果返回
return json(['info'=>$arr]);
}
return json(['status'=>0,'msg'=>"文件不存在"]);
}
}

/**
* 将Base64数据转换成二进制并存储到指定路径
* @param $base64
* @param string $path
* liwei
* @return array
*/
public function new_base64_upload($base64, $path = '') {
$data = explode(',',$base64);
trace($data,'api');
unset($base64);
if (count($data) !== 2){
return['status'=>0,'msg'=>'文件格式错误'];
}
$image_name =time().'.png';
$image_path = "./uploads/hidden-danger/";
$image_file = $image_path . $image_name;
//服务器文件存储路径
try {
if (file_put_contents($image_file, base64_decode($data[1]))) {
return['status'=>200, 'msg'=>'成功', 'data'=>['name' => $image_name, 'path' => $image_path]];
} else {
return['status'=>0,'msg'=> '文件保存失败'];
}
}catch (\Exception $e){
$msg = $e->getMessage();
return['status'=>0,'msg'=>$msg];
}
}

$flag 上一页 下一页