Com.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace app\mobile\controller;
  3. use app\common\model\Attachment as AttachmentModel;
  4. class Com
  5. {
  6. /**
  7. * 图片上传
  8. */
  9. public function imageUpload()
  10. {
  11. $file = input('post.file');
  12. $name = input('post.name');
  13. $ext = pathinfo($name)['extension'];
  14. if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
  15. $this->error('文件后缀必须为jpg,jpeg,png');
  16. }
  17. if ($file) {
  18. //创建目录
  19. $upload_dir = public_path() . 'public/attachment/images/' . date('Ymd');
  20. if (!is_dir($upload_dir)) {
  21. mkdir($upload_dir, '0777', true);
  22. }
  23. //保存文件
  24. $file_name = $this->_file_name($ext);
  25. $file_path = '/attachment/images/' . $file_name;
  26. $is_upload = $this->_base64_image_content($file, $file_path);
  27. if (!$is_upload) {
  28. page_result(1, "上传失败,请重新上传");
  29. }
  30. $attachment = request()->domain() . $file_path;
  31. AttachmentModel::create([
  32. 'filename' => $name,
  33. 'atype' => 1,
  34. 'attachment' => $attachment,
  35. 'createtime' => time(),
  36. ]);
  37. page_result(0, '', ['avatar' => $attachment]);
  38. } else {
  39. page_result(1, "请上传文件");
  40. }
  41. }
  42. private function _file_name($ext)
  43. {
  44. //生成随机文件名
  45. //定义一个包含大小写字母数字的字符串
  46. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  47. //把字符串分割成数组
  48. $newchars = str_split($chars);
  49. //打乱数组
  50. shuffle($newchars);
  51. //从数组中随机取出15个字符
  52. $chars_key = array_rand($newchars, 15);
  53. //把取出的字符重新组成字符串
  54. $fnstr = '';
  55. for ($i = 0; $i < 15; $i++) {
  56. $fnstr .= $newchars[$chars_key[$i]];
  57. }
  58. //输出文件名并做MD5加密
  59. return md5($fnstr . microtime(true) * 1000) . '.' . $ext;
  60. }
  61. private function _base64_image_content($base64_image_content, $file_url_path)
  62. {
  63. //匹配出图片的格式
  64. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
  65. $content = base64_decode(str_replace($result[1], '', $base64_image_content));
  66. $file_path = public_path('') . 'public' . $file_url_path;
  67. if (file_put_contents($file_path, $content)) {
  68. return true;
  69. } else {
  70. return false;
  71. }
  72. } else {
  73. return false;
  74. }
  75. }
  76. }