Browse Source

网络图片链接地址上传

master
wanghongjun 6 months ago
parent
commit
071fd1fd9c
  1. 68
      app/common/controller/Upload.php
  2. 3
      app/lang/en_us.php
  3. 1
      app/lang/zh_cn.php

68
app/common/controller/Upload.php

@ -198,6 +198,25 @@ class Upload extends BaseController
}
}
public function uploadFileImage()
{
$param=$this->request->param();
try{
$image_url=$param['image_url']??'';
if (empty($image_url)) {
throw new \Exception(lang('file.exist'));
}
$data = $this->downloadImage($image_url);
if (!$data['status']) {
throw new \Exception(lang('file.error'));
}
$info=$this->upload($param,$data['path'],'', false);
return success(lang('file.uploadOk'),$info);
} catch(\Exception $e) {
return error($e->getMessage());
}
}
// 获取上传文件的信息
protected function getFileInfo($file,$path,$isObj=false){
@ -577,4 +596,53 @@ class Upload extends BaseController
// 返回平均颜色
return imagecolorallocatealpha($image, $avgR, $avgG, $avgB, $avgAlpha);
}
protected function downloadImage($url, $savePath = 'temp')
{
try {
// 验证URL有效性
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new \Exception("无效的图片URL");
}
// 创建存储目录(递归创建)
$savePath .= '/'. date("Y-m-d");
$rootPath = public_path();
$fullPath = $rootPath . $savePath;
if (!is_dir($fullPath)) {
mkdir($fullPath, 0755, true);
}
// 获取图片内容(使用cURL)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过SSL验证
$imageData = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200 || !$imageData) {
throw new \Exception("图片下载失败,HTTP状态码: {$httpCode}");
}
curl_close($ch);
// 生成唯一文件名
$ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
$ext = $ext ?: 'jpg'; // 默认jpg格式
$filename = date('YmdHis') . '_' . uniqid() . '.' . $ext;
// 保存文件
$localPath = $fullPath . '/' . $filename;
if (!file_put_contents($localPath, $imageData)) {
throw new \Exception("文件保存失败");
}
// 返回相对路径(适用于web访问)
return ['status' => 1, 'path' => $savePath . '/' . $filename];
} catch (\Exception $e) {
return ['status' => 0];
}
}
}

3
app/lang/en_us.php

@ -155,7 +155,8 @@ return [
'browserDown' => "Please use the browser to download",
'exist' => "The file does not exist", // Note: This might be a duplicate of 'preview' and could be replaced with a more specific message
'uploadLimit' => "File size cannot exceed {:size}MB",
'typeNotSupport' => "File format is not supported",
'typeNotSupport' => "File format is not supported",
'error'=>"Upload failed",
'uploadOk' => "Upload successful",
],
'scan' => [

1
app/lang/zh_cn.php

@ -155,6 +155,7 @@ return [
'exist'=>"文件不存在",
'uploadLimit'=>"文件大小不能超过{:size}MB",
'typeNotSupport'=>"文件格式不支持",
'error'=>"上传失败",
'uploadOk'=>"上传成功"
],
'scan'=>[

Loading…
Cancel
Save