资讯专栏INFORMATION COLUMN

整合百度UEditor上传图片到阿里云OSS

suosuopuo / 3788人阅读

摘要:前言将图片上传到阿里云是一种趋势,一个必然。如果直接把图片上传到阿里云是比较简单的,应该很多人都懂,但是用百度上传图片到阿里云,就没那么简单了,所以我感觉还是有必要写这篇文章分享出来,给有需要的人。

前言

将图片上传到阿里云OSS是一种趋势,一个必然。当你的项目图片过多,需要频繁上传和替换的时候,用阿里云OSS可以很方便的管理你的图片,节省服务器空间,大大提高了效率。阿里云OSS是阿里云提供的海量、安全、低成本、高可靠的云存储服务。你可以通过调用API,在任何应用、任何时间、任何地点上传和下载数据,也可以通过Web控制台对数据进行简单的管理。阿里云OSS适合存放任意类型的文件,适合各种网站、开发企业及开发者使用。

如果直接把图片上传到阿里云OSS是比较简单的,应该很多人都懂,但是用百度UEditor上传图片到阿里云OSS,就没那么简单了,所以我感觉还是有必要写这篇文章分享出来,给有需要的人。

效果图

修改百度UEditor的文件

1、修改这几个文件:

1.1、修改Uploader.class.php文件

注意:修改的部分我有加注释,注意看。

</>复制代码

  1. "临时文件错误",
  2. "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
  3. "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
  4. "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
  5. "ERROR_CREATE_DIR" => "目录创建失败",
  6. "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
  7. "ERROR_FILE_MOVE" => "文件保存时出错",
  8. "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
  9. "ERROR_WRITE_CONTENT" => "写入文件内容错误",
  10. "ERROR_UNKNOWN" => "未知错误",
  11. "ERROR_DEAD_LINK" => "链接不可用",
  12. "ERROR_HTTP_LINK" => "链接不是http链接",
  13. "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确"
  14. );
  15. /**
  16. * 构造函数
  17. * @param string $fileField 表单名称
  18. * @param array $config 配置项
  19. * @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
  20. */
  21. public function __construct($fileField, $config, $type = "upload")
  22. {
  23. $this->fileField = $fileField;
  24. $this->config = $config;
  25. $this->type = $type;
  26. if ($type == "remote") {
  27. $this->saveRemote();
  28. } else if($type == "base64") {
  29. $this->upBase64();
  30. } else {
  31. $this->upFile();
  32. }
  33. $this->stateMap["ERROR_TYPE_NOT_ALLOWED"] = iconv("unicode", "utf-8", $this->stateMap["ERROR_TYPE_NOT_ALLOWED"]);
  34. }
  35. /**
  36. * 上传文件的主处理方法
  37. * @return mixed
  38. */
  39. private function upFile()
  40. {
  41. $file = $this->file = $_FILES[$this->fileField];
  42. if (!$file) {
  43. $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
  44. return;
  45. }
  46. if ($this->file["error"]) {
  47. $this->stateInfo = $this->getStateInfo($file["error"]);
  48. return;
  49. } else if (!file_exists($file["tmp_name"])) {
  50. $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
  51. return;
  52. } else if (!is_uploaded_file($file["tmp_name"])) {
  53. $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
  54. return;
  55. }
  56. //修改:上传阿里云OSS
  57. $upload=new sourcecorewidgetsuploadFileUpload();
  58. $Pictureinfo=$upload->UploadUeditorPicture($file);
  59. $this->oriName = $file["name"];
  60. $this->fileSize = $file["size"];
  61. $this->fileType = $this->getFileExt();
  62. $this->fullName = "/".$Pictureinfo["path"];
  63. $this->filePath = $Pictureinfo["path"];
  64. $this->fileName = $this->getFileName();
  65. $dirname = dirname($this->filePath);
  66. //检查文件大小是否超出限制
  67. if (!$this->checkSize()) {
  68. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  69. return;
  70. }
  71. //检查是否不允许的文件格式
  72. if (!$this->checkType()) {
  73. $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
  74. return;
  75. }
  76. //创建目录失败
  77. // if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  78. // $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  79. // return;
  80. // } else if (!is_writeable($dirname)) {
  81. // $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  82. // return;
  83. // }
  84. $this->stateInfo = $this->stateMap[0];
  85. //移动文件
  86. // if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
  87. // $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
  88. // } else { //移动成功
  89. // $this->stateInfo = $this->stateMap[0];
  90. // }
  91. }
  92. /**
  93. * 处理base64编码的图片上传
  94. * @return mixed
  95. */
  96. private function upBase64()
  97. {
  98. $base64Data = $_POST[$this->fileField];
  99. $img = base64_decode($base64Data);
  100. $this->oriName = $this->config["oriName"];
  101. $this->fileSize = strlen($img);
  102. $this->fileType = $this->getFileExt();
  103. $this->fullName = $this->getFullName();
  104. $this->filePath = $this->getFilePath();
  105. $this->fileName = $this->getFileName();
  106. $dirname = dirname($this->filePath);
  107. //检查文件大小是否超出限制
  108. if (!$this->checkSize()) {
  109. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  110. return;
  111. }
  112. //创建目录失败
  113. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  114. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  115. return;
  116. } else if (!is_writeable($dirname)) {
  117. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  118. return;
  119. }
  120. //移动文件
  121. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  122. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  123. } else { //移动成功
  124. $this->stateInfo = $this->stateMap[0];
  125. }
  126. }
  127. /**
  128. * 拉取远程图片
  129. * @return mixed
  130. */
  131. private function saveRemote()
  132. {
  133. $imgUrl = htmlspecialchars($this->fileField);
  134. $imgUrl = str_replace("&", "&", $imgUrl);
  135. //http开头验证
  136. if (strpos($imgUrl, "http") !== 0) {
  137. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
  138. return;
  139. }
  140. //获取请求头并检测死链
  141. $heads = get_headers($imgUrl);
  142. if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
  143. $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
  144. return;
  145. }
  146. //格式验证(扩展名验证和Content-Type验证)
  147. $fileType = strtolower(strrchr($imgUrl, "."));
  148. if (!in_array($fileType, $this->config["allowFiles"]) || stristr($heads["Content-Type"], "image")) {
  149. $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
  150. return;
  151. }
  152. //打开输出缓冲区并获取远程图片
  153. ob_start();
  154. $context = stream_context_create(
  155. array("http" => array(
  156. "follow_location" => false // don"t follow redirects
  157. ))
  158. );
  159. readfile($imgUrl, false, $context);
  160. $img = ob_get_contents();
  161. ob_end_clean();
  162. preg_match("/[/]([^/]*)[.]?[^./]*$/", $imgUrl, $m);
  163. $this->oriName = $m ? $m[1]:"";
  164. $this->fileSize = strlen($img);
  165. $this->fileType = $this->getFileExt();
  166. $this->fullName = $this->getFullName();
  167. $this->filePath = $this->getFilePath();
  168. $this->fileName = $this->getFileName();
  169. $dirname = dirname($this->filePath);
  170. //检查文件大小是否超出限制
  171. if (!$this->checkSize()) {
  172. $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
  173. return;
  174. }
  175. //创建目录失败
  176. if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
  177. $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
  178. return;
  179. } else if (!is_writeable($dirname)) {
  180. $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
  181. return;
  182. }
  183. //移动文件
  184. if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
  185. $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
  186. } else { //移动成功
  187. $this->stateInfo = $this->stateMap[0];
  188. }
  189. }
  190. /**
  191. * 上传错误检查
  192. * @param $errCode
  193. * @return string
  194. */
  195. private function getStateInfo($errCode)
  196. {
  197. return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
  198. }
  199. /**
  200. * 获取文件扩展名
  201. * @return string
  202. */
  203. private function getFileExt()
  204. {
  205. return strtolower(strrchr($this->oriName, "."));
  206. }
  207. /**
  208. * 重命名文件
  209. * @return string
  210. */
  211. private function getFullName()
  212. {
  213. //替换日期事件
  214. $t = time();
  215. $d = explode("-", date("Y-y-m-d-H-i-s"));
  216. $format = $this->config["pathFormat"];
  217. $format = str_replace("{yyyy}", $d[0], $format);
  218. $format = str_replace("{yy}", $d[1], $format);
  219. $format = str_replace("{mm}", $d[2], $format);
  220. $format = str_replace("{dd}", $d[3], $format);
  221. $format = str_replace("{hh}", $d[4], $format);
  222. $format = str_replace("{ii}", $d[5], $format);
  223. $format = str_replace("{ss}", $d[6], $format);
  224. $format = str_replace("{time}", $t, $format);
  225. //过滤文件名的非法自负,并替换文件名
  226. $oriName = substr($this->oriName, 0, strrpos($this->oriName, "."));
  227. $oriName = preg_replace("/[|?"<>/*]+/", "", $oriName);
  228. $format = str_replace("{filename}", $oriName, $format);
  229. //替换随机字符串
  230. $randNum = rand(1, 10000000000) . rand(1, 10000000000);
  231. if (preg_match("/{rand:([d]*)}/i", $format, $matches)) {
  232. $format = preg_replace("/{rand:[d]*}/i", substr($randNum, 0, $matches[1]), $format);
  233. }
  234. $ext = $this->getFileExt();
  235. return $format . $ext;
  236. }
  237. /**
  238. * 获取文件名
  239. * @return string
  240. */
  241. private function getFileName () {
  242. return substr($this->filePath, strrpos($this->filePath, "/") + 1);
  243. }
  244. /**
  245. * 获取文件完整路径
  246. * @return string
  247. */
  248. private function getFilePath()
  249. {
  250. $fullname = $this->fullName;
  251. // $rootPath = $_SERVER["DOCUMENT_ROOT"];
  252. // if (substr($fullname, 0, 1) != "/") {
  253. // $fullname = "/" . $fullname;
  254. // }
  255. //修改:替换路径
  256. return $fullname;
  257. }
  258. /**
  259. * 文件类型检测
  260. * @return bool
  261. */
  262. private function checkType()
  263. {
  264. return in_array($this->getFileExt(), $this->config["allowFiles"]);
  265. }
  266. /**
  267. * 文件大小检测
  268. * @return bool
  269. */
  270. private function checkSize()
  271. {
  272. return $this->fileSize <= ($this->config["maxSize"]);
  273. }
  274. /**
  275. * 获取当前上传成功文件的各项信息
  276. * @return array
  277. */
  278. public function getFileInfo()
  279. {
  280. return array(
  281. "state" => $this->stateInfo,
  282. "url" => $this->fullName,
  283. "title" => $this->fileName,
  284. "original" => $this->oriName,
  285. "type" => $this->fileType,
  286. "size" => $this->fileSize
  287. );
  288. }
  289. }

1.2、修改config.json文件,这个文件主要是修改图片路径,改为你的阿里云OSS的路径

</>复制代码

  1. /* 前后端通信相关的配置,注释只允许使用多行方式 */
  2. {
  3. /* 上传图片配置项 */
  4. "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
  5. "imageFieldName": "upfile", /* 提交的图片表单名称 */
  6. "imageMaxSize": 2048000, /* 上传大小限制,单位B */
  7. "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
  8. "imageCompressEnable": true, /* 是否压缩图片,默认是true */
  9. "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
  10. "imageInsertAlign": "none", /* 插入的图片浮动方式 */
  11. "imageUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 图片访问路径前缀 */
  12. "imagePathFormat": "data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
  13. /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
  14. /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
  15. /* {time} 会替换成时间戳 */
  16. /* {yyyy} 会替换成四位年份 */
  17. /* {yy} 会替换成两位年份 */
  18. /* {mm} 会替换成两位月份 */
  19. /* {dd} 会替换成两位日期 */
  20. /* {hh} 会替换成两位小时 */
  21. /* {ii} 会替换成两位分钟 */
  22. /* {ss} 会替换成两位秒 */
  23. /* 非法字符 : * ? " < > | */
  24. /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */
  25. /* 涂鸦图片上传配置项 */
  26. "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
  27. "scrawlFieldName": "upfile", /* 提交的图片表单名称 */
  28. "scrawlPathFormat": "data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
  29. "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
  30. "scrawlUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 图片访问路径前缀 */
  31. "scrawlInsertAlign": "none",
  32. /* 截图工具上传 */
  33. "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
  34. "snapscreenPathFormat": "/data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
  35. "snapscreenUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 图片访问路径前缀 */
  36. "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */
  37. /* 抓取远程图片配置 */
  38. "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
  39. "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
  40. "catcherFieldName": "source", /* 提交的图片列表表单名称 */
  41. "catcherPathFormat": "/data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
  42. "catcherUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 图片访问路径前缀 */
  43. "catcherMaxSize": 2048000, /* 上传大小限制,单位B */
  44. "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */
  45. /* 上传视频配置 */
  46. "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
  47. "videoFieldName": "upfile", /* 提交的视频表单名称 */
  48. "videoPathFormat": "/data/attachment/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
  49. "videoUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 视频访问路径前缀 */
  50. "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
  51. "videoAllowFiles": [
  52. ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
  53. ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */
  54. /* 上传文件配置 */
  55. "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
  56. "fileFieldName": "upfile", /* 提交的文件表单名称 */
  57. "filePathFormat": "/data/attachment/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
  58. "fileUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 文件访问路径前缀 */
  59. "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
  60. "fileAllowFiles": [
  61. ".png", ".jpg", ".jpeg", ".gif", ".bmp",
  62. ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
  63. ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
  64. ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
  65. ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
  66. ], /* 上传文件格式显示 */
  67. /* 列出指定目录下的图片 */
  68. "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
  69. "imageManagerListPath": "/data/attachment/image/", /* 指定要列出图片的目录 */
  70. "imageManagerListSize": 20, /* 每次列出文件数量 */
  71. "imageManagerUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 图片访问路径前缀 */
  72. "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
  73. "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */
  74. /* 列出指定目录下的文件 */
  75. "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
  76. "fileManagerListPath": "/data/attachment/file/", /* 指定要列出文件的目录 */
  77. "fileManagerUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 文件访问路径前缀 */
  78. "fileManagerListSize": 20, /* 每次列出文件数量 */
  79. "fileManagerAllowFiles": [
  80. ".png", ".jpg", ".jpeg", ".gif", ".bmp",
  81. ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
  82. ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
  83. ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
  84. ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
  85. ] /* 列出的文件类型 */
  86. }

1.3、action_upload.php、action_list.php、action_crawler.php这三个文件主要是引用上传到阿里云OSS的文件FileUpload.php,都加入如下代码即可

</>复制代码

  1. include (__DIR__."/../../../../../../source/core/widgets/upload/FileUpload.php");
FileUpload.php文件上传到阿里云OSS的代码

</>复制代码

  1. 1,"modules_name"=>"ueditor","user_id"=>1];
  2. $model = array();
  3. $bucket = "test";
  4. if(empty($data["id"])){
  5. $model["status"]="ID不能为空";
  6. return $model;
  7. }
  8. if(!isset($data["modules_name"])){
  9. $model["status"]="模块名称不能为空";
  10. return $model;
  11. }
  12. if(!isset($data["user_id"])){
  13. $model["status"]="用户id不能为空";
  14. return $model;
  15. }
  16. $path = self::Encrypt($data["modules_name"],$data["id"],$data["user_id"]);//对上传的路径加密
  17. if(!empty($file)){
  18. $randName = time() . rand(1000, 9999) . strtolower(strrchr($file["name"], "."));
  19. $name = $path.$randName;
  20. $tempName=!empty($file["tmp_name"])?$file["tmp_name"]:"";
  21. $ossClient->uploadFile($bucket,$name,$tempName);
  22. return ["path"=>$name,"randName"=>$randName];
  23. }
  24. return ["path"=>"","randName"=>""];
  25. }
  26. /**
  27. * 删除附件
  28. *
  29. * @param path string y upload表返回的附件上传路径path 字段
  30. * @return status string 结果信息
  31. */
  32. static public function DownloadDelete($path)
  33. {
  34. $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);
  35. $bucket = "test";
  36. if(!isset($path)){
  37. $model["status"]="附件路径不能为空";
  38. return $model;
  39. }
  40. $ossClient->deleteObject($bucket, $path);
  41. $model["status"]="删除成功";
  42. return $model;
  43. }
  44. /**
  45. * 批量删除附件
  46. *
  47. * @param path string y upload表返回的附件上传路径path 字段
  48. * @return status string 结果信息
  49. */
  50. static public function DownloadDeletes($data)
  51. {
  52. $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);
  53. $bucket = "test";
  54. if(!isset($data)){
  55. $model["status"]="删除数组不能为空";
  56. return $model;
  57. }
  58. $ossClient->deleteObjects($bucket, $data);
  59. $model["status"]="删除成功";
  60. return $model;
  61. }
  62. function getObject($object)
  63. {
  64. $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);
  65. $options = array();
  66. $bucket = "test";
  67. $timeout = 3600;
  68. $options = NULL;
  69. try {
  70. $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT");
  71. } catch (OssException $e) {
  72. printf(__FUNCTION__ . ": FAILED
  73. ");
  74. printf($e->getMessage() . "
  75. ");
  76. return;
  77. }
  78. print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "
  79. ");
  80. $content = file_get_contents(__FILE__);
  81. $request = new RequestCore($signedUrl);
  82. $request->set_method("PUT");
  83. $request->add_header("Content-Type", "");
  84. $request->add_header("Content-Length", strlen($content));
  85. $request->set_body($content);
  86. $request->send_request();
  87. $res = new ResponseCore($request->get_response_header(),
  88. $request->get_response_body(), $request->get_response_code());
  89. if ($res->isOK()) {
  90. print(__FUNCTION__ . ": OK" . "
  91. ");
  92. } else {
  93. print(__FUNCTION__ . ": FAILED" . "
  94. ");
  95. };
  96. }
  97. /**
  98. * 加密路径
  99. *
  100. * @param array $data Y 参数数组(array("modules_name"=>$modules_name,"bucket"=>"test","path"=>"upload/accessory/14585506176746.jpg"))
  101. * --modules_name string Y 模块名称
  102. * --id string Y id
  103. * @return status string 结果信息
  104. */
  105. static public function Encrypt($modules_name,$id,$user_id="")
  106. {
  107. if(empty($user_id)){
  108. $user_id = Yii::$app->user->id;
  109. }
  110. $modules_path = AesMask::encrypt($modules_name,"test");
  111. $id_path = AesMask::encrypt($id,"test");
  112. return "test/".$modules_path."/".$id_path."/";
  113. }
  114. }
  115. ?>
新增图片Controller的代码

</>复制代码

  1. public function actionCreate()
  2. {
  3. $username=!empty(Yii::$app->user->identity->attributes["username"])?Yii::$app->user->identity->attributes["username"]:"";
  4. $model = new Product();
  5. $model->user_id=Yii::$app->user->id;
  6. $model->user_name = $username;
  7. $model->product_type=$this->product_type;
  8. $model->loadDefaultValues();
  9. $bodyModel = $this->getBodyModel();
  10. $bodyModel->loadDefaultValues();
  11. if(($r = $this->saveProduct($model, $bodyModel))!==false)
  12. {
  13. return $r;
  14. }
  15. //产品属性
  16. $product_items=[];
  17. return $this->render("create", [
  18. "model" => $model,
  19. "bodyModel" => $bodyModel,
  20. "product_items"=>$product_items,
  21. ]);
  22. }
  23. public function saveProduct($model, $bodyModel)
  24. {
  25. $postDatas = Yii::$app->request->post();
  26. if ($model->load($postDatas) && $bodyModel->load($postDatas) && $model->validate() && $bodyModel->validate()) {
  27. if($model->summary===null|| $model->summary ==="")
  28. {
  29. if($bodyModel->hasAttribute("body"))
  30. {
  31. $product = strip_tags($bodyModel->body);
  32. $pattern = "/s/";//去除空白
  33. $product = preg_replace($pattern, "", $product);
  34. $model->summary=StringHelper::subStr($product,250);
  35. }
  36. }
  37. if($model->save())
  38. {
  39. $bodyModel->product_id = $model->id;
  40. $bodyModel->save();
  41. //保存百度编辑器的图片
  42. $this->saveUpload($bodyModel->body,$model->id);
  43. //属性
  44. if(!empty($postDatas["ProductItems"])){
  45. ProductItems::deleteAll(["product_id"=>$model->id]);
  46. foreach ($postDatas["ProductItems"]["type"] as $key => $val) {
  47. $modelItems = new ProductItems();
  48. $modelItems->product_id = $model->id;
  49. $modelItems->type = !empty($postDatas["ProductItems"]["type"][$key])?$postDatas["ProductItems"]["type"][$key]:"";
  50. $modelItems->source = !empty($postDatas["ProductItems"]["source"][$key])?$postDatas["ProductItems"]["source"][$key]:"";
  51. $modelItems->ticket_pat = !empty($postDatas["ProductItems"]["ticket_pat"][$key])?$postDatas["ProductItems"]["ticket_pat"][$key]:"";
  52. $modelItems->ticket_pats = !empty($postDatas["ProductItems"]["ticket_pats"][$key])?$postDatas["ProductItems"]["ticket_pats"][$key]:"";
  53. $modelItems->save();
  54. }
  55. }
  56. return $this->redirect(["index"]);
  57. }
  58. }
  59. return false;
  60. }
  61. //保存图片
  62. public function saveUpload($body,$task_id)
  63. {
  64. $error["status"]="内容为空";
  65. if(!empty($body) && $task_id){
  66. $preg = "//i"; //获取百度编辑器里提交的图片路径
  67. preg_match_all($preg, $body, $imgArr);
  68. if(!empty($imgArr[1])){
  69. foreach ($imgArr[1] as $key => $val) {
  70. $_imgArr = explode("/wpzx/", $val);
  71. $path="wpzx/".$_imgArr[1];
  72. $suffix = pathinfo($_imgArr[1]);
  73. $img_info = getimagesize($val);
  74. $model= new Upload();
  75. if($suffix["extension"] == "jpg" || $suffix["extension"] == "JPG"|| $suffix["extension"] == "png"|| $suffix["extension"] == "PNG"|| $suffix["extension"] == "jpeg"){
  76. $model->thumb = $path;
  77. }
  78. $model->task_id = $task_id;
  79. $model->name = $suffix["basename"];
  80. $model->path = $path;
  81. $model->status = 1;
  82. $model->user_id = Yii::$app->user->id;
  83. $model->size = $img_info[0]*$img_info[1];
  84. $model->type = $img_info["mime"];
  85. $model->upload_time = time();
  86. $model->module_id = 3;
  87. $model->modules_name = "product";
  88. $model->target = 1;
  89. if (!$model->save()) {
  90. $error["status"]="失败";
  91. }
  92. }
  93. if($error["status"]!="失败"){
  94. return true;
  95. }
  96. return $error;
  97. }
  98. }
  99. //删除upload与阿里云的图片
  100. $upload=Upload::getUploadsAll($task_id,"product");
  101. if(!empty($upload)){
  102. FileUpload::DownloadDeletes(ArrayHelper::getColumn($upload, "path"));
  103. Upload::deleteAll(["task_id"=>$task_id,"modules_name"=>"product"]);
  104. }
  105. }
  106. //根据指定条件获取所有上传图片
  107. public static function getUploadsAll($task_id,$modules_name)
  108. {
  109. $data=[];
  110. $query=Upload::find()->where(["modules_name"=>$modules_name]);
  111. if(!empty($task_id)){
  112. $data=$query->andWhere(["task_id"=>$task_id])->all();
  113. }else{
  114. $data=$query->all();
  115. }
  116. return $data;
  117. }
  118. //upload表的字段如下,仅供参考
  119. public function attributeLabels()
  120. {
  121. return [
  122. "id" => "ID",
  123. "name" => "上传文件名",
  124. "path" => "文件路径",
  125. "status" => "上传状态",
  126. "task_id" => "所属任务",
  127. "user_id" => "所属用户",
  128. "size" => "文件大小",
  129. "type" => "文件类型",
  130. "upload_time" => "上传时间",
  131. "module_id" => "所属系统",
  132. "thumb" => "缩略图",
  133. ];
  134. }
新增图片Views的代码

</>复制代码

  1. "{label}{input}
  2. {error}",
  3. "labelOptions" => [
  4. "class" => "control-label"
  5. ]
  6. ]
  7. ;
  8. $takonomies = Takonomy::getArrayTree("product");
  9. $options = Common::buildTreeOptions($takonomies, $model->takonomy_id);
  10. ?>
  11. [
  12. "enctype"=>"multipart/form-data",
  13. ],
  14. "fieldConfig" => [
  15. "template" => "{label}
    {input}
  16. {error}",
  17. "labelOptions" => [
  18. "class" => "col-md-4 control-label no-padding-left no-padding-right align-left"
  19. ]
  20. ],
  21. ]);
  22. ?>
  23. field($model, "title",$filedOptions)->textInput(["maxlength" => 256,"placeholder"=>"请输入标题"])?>
  24. field($model, "url_alias",$filedOptions)->textInput(["maxlength" => 128,"placeholder"=>"Url 地址"])?>

  25. field($bodyModel, "body",$filedOptions)->widget(Ueditor::className(),[
  26. "options"=>[
  27. "focus"=>true,
  28. "toolbars"=> [
  29. ["fullscreen", "source", "|", "undo", "redo", "|", "bold", "italic", "underline","removeformat","autotypeset", "|", "forecolor", "backcolor", "selectall", "cleardoc","|","fontfamily", "fontsize", "|", "justifyleft", "justifycenter", "|", "link", "unlink","|", "insertimage", "emotion","attachment","|", "preview", "searchreplace"]
  30. ],
  31. ],
  32. "attributes"=>[
  33. "style"=>"height:80px"
  34. ]
  35. ])?>
  36. isNewRecord ? "新建" : "编辑", ["class" => $model->isNewRecord ? "btn btn-success" : "btn btn-primary"])?>
总结分析

1、要修改的地方还是挺多的,百度UEditor上传后获取图片路径保存到数据库处理起来也有点繁琐,如果你们有更好的方法,可以给我留言,咱们一块讨论。

2、以上我只是处理了图片上传到阿里云OSS,如果大家需要把视频,Mp3等等附件上传到阿里云OSS也是同样的方法,唯一的区别就是在提交表单的时候要获取到对应的视频,Mp3等等附件路径保存到数据库得处理一下。

相关资料

PHP-SDK 下载安装地址
ueditor 下载地址

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/25863.html

相关文章

  • SpringBoot 整合 阿里OSS 存储服务,快来免费搭建一个自己的图床

    摘要:笔主很早就开始用阿里云存储服务当做自己的图床了。阿里云对象存储文档,本篇文章会介绍到整合阿里云存储服务实现文件上传下载以及简单的查看。 Github 地址:https://github.com/Snailclimb/springboot-integration-examples(SpringBoot和其他常用技术的整合,可能是你遇到的讲解最详细的学习案例,力争新手也能看懂并且能够在看完...

    邹强 评论0 收藏0
  • TP5整合阿里OSS上传文件第二节,异步上传头像(下)

    摘要:找到头像下面的添加一个的样式类将内容改变成上传成功并且显示上传成功文件上传失败,同样是添加找到头像下面的添加一个的样式类将内容改变成上传失败并且显示上传失败完成上传完了,成功或者失败,先删除进度条。 是这个功能的最后一步了,新增插件:layer.js 弹窗层组件jquery.form 异步表单提交插件 新增CSS:layer扩展文件 修改layer弹窗的皮肤,默认的不喜欢!基本代码和之...

    dmlllll 评论0 收藏0
  • TP5整合阿里OSS上传文件第二节,异步上传头像(下)

    摘要:找到头像下面的添加一个的样式类将内容改变成上传成功并且显示上传成功文件上传失败,同样是添加找到头像下面的添加一个的样式类将内容改变成上传失败并且显示上传失败完成上传完了,成功或者失败,先删除进度条。 是这个功能的最后一步了,新增插件:layer.js 弹窗层组件jquery.form 异步表单提交插件 新增CSS:layer扩展文件 修改layer弹窗的皮肤,默认的不喜欢!基本代码和之...

    qiangdada 评论0 收藏0
  • TP5整合阿里OSS上传文件第二节,异步上传头像(下)

    摘要:找到头像下面的添加一个的样式类将内容改变成上传成功并且显示上传成功文件上传失败,同样是添加找到头像下面的添加一个的样式类将内容改变成上传失败并且显示上传失败完成上传完了,成功或者失败,先删除进度条。 是这个功能的最后一步了,新增插件:layer.js 弹窗层组件jquery.form 异步表单提交插件 新增CSS:layer扩展文件 修改layer弹窗的皮肤,默认的不喜欢!基本代码和之...

    draveness 评论0 收藏0
  • TP5整合阿里OSS上传文件第二节,异步上传头像(下)

    摘要:找到头像下面的添加一个的样式类将内容改变成上传成功并且显示上传成功文件上传失败,同样是添加找到头像下面的添加一个的样式类将内容改变成上传失败并且显示上传失败完成上传完了,成功或者失败,先删除进度条。 是这个功能的最后一步了,新增插件:layer.js 弹窗层组件jquery.form 异步表单提交插件 新增CSS:layer扩展文件 修改layer弹窗的皮肤,默认的不喜欢!基本代码和之...

    Dongjie_Liu 评论0 收藏0

发表评论

0条评论

suosuopuo

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<