AssetsController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-03-09 22:07
  7. */
  8. namespace backend\controllers;
  9. use Yii;
  10. use backend\widgets\ueditor\UeditorAction;
  11. use yii\helpers\FileHelper;
  12. use yii\web\Response;
  13. use yii\web\UploadedFile;
  14. class AssetsController extends \yii\web\Controller
  15. {
  16. public function actions()
  17. {
  18. return [
  19. 'ueditor' => [
  20. 'class' => UeditorAction::className(),
  21. ],
  22. ];
  23. }
  24. public function actionWebuploader()
  25. {
  26. Yii::$app->getResponse()->format = Response::FORMAT_JSON;
  27. $upload = UploadedFile::getInstanceByName("file");
  28. if ($upload !== null) {
  29. if( !in_array(strtolower($upload->getExtension()), ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']) ){
  30. return [
  31. "code"=>1,
  32. "msg" => Yii::t("app", 'Only picture allowed'),
  33. ];
  34. }
  35. $uploadPath = Yii::getAlias("@uploads/webuploader");
  36. if( strpos(strrev($uploadPath), '/') !== 0 ) $uploadPath .= '/';
  37. if (! FileHelper::createDirectory($uploadPath)) {
  38. return [
  39. 'code' => 0,
  40. 'msg' => Yii::t('app', "Create directory failed " . $uploadPath)
  41. ];
  42. }
  43. $fullName = isset($options['filename']) ? $uploadPath . uniqid() : $uploadPath . date('YmdHis') . '_' . uniqid() . '.' . $upload->getExtension();
  44. if (! $upload->saveAs($fullName)) {
  45. return[
  46. 'code' => 1,
  47. 'msg' => Yii::t('app', 'Upload {attribute} error: ' . $upload->error, ['attribute' => Yii::t('app', "File")])
  48. ] ;
  49. }
  50. $attachment = str_replace(Yii::getAlias('@frontend/web'), '', $fullName);
  51. /* @var $cdn \feehi\cdn\TargetInterface */
  52. $cdn = Yii::$app->get('cdn');
  53. $cdn->upload($fullName, $attachment);
  54. return [
  55. "code" => 0,
  56. "url" => $cdn->getCdnUrl($attachment),
  57. "attachment" => $attachment
  58. ];
  59. }
  60. return [
  61. "code"=>1,
  62. "msg" => Yii::t("app", 'File cannot be empty'),
  63. ];
  64. }
  65. }