FileController.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace html5\controllers;
  3. use Yii;
  4. use common\helpers\ResultHelper;
  5. use common\helpers\StringHelper;
  6. use common\helpers\FileHelper;
  7. use common\traits\FileAction;
  8. /**
  9. * Class FileController
  10. * @package wechat\controllers
  11. * @author jianyan74 <751393839@qq.com>
  12. */
  13. class FileController extends BaseController
  14. {
  15. use FileAction;
  16. /**
  17. * @var array
  18. */
  19. protected $extend = [
  20. 'images' => '.jpg',
  21. 'videos' => '.mp4',
  22. 'voices' => '.mp3',
  23. ];
  24. /**
  25. * 下载微信临时资源
  26. *
  27. * @return array
  28. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  29. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  30. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  31. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  32. * @throws \GuzzleHttp\Exception\GuzzleException
  33. * @throws \Psr\SimpleCache\InvalidArgumentException
  34. * @throws \yii\web\UnprocessableEntityHttpException
  35. */
  36. public function actionDownload()
  37. {
  38. $mediaId = Yii::$app->request->post('media_id');
  39. $type = Yii::$app->request->post('type', 'images');
  40. $config = Yii::$app->params['uploadConfig'][$type];
  41. $stream = Yii::$app->wechat->app->media->get($mediaId);
  42. // 验证接口是否报错
  43. if ($error = Yii::$app->services->base->getWechatError($stream, false)) {
  44. return ResultHelper::json(422, $error);
  45. }
  46. // 文件后缀
  47. $fileExc = $this->extend[$type];
  48. $filePath = $config['path'] . date($config['subName'], time()) . "/";
  49. $fileName = $config['prefix'] . time() . StringHelper::random(8, true);
  50. $relativePath = Yii::getAlias("@attachurl/") . $filePath; // 相对路径
  51. $absolutePath = Yii::getAlias("@attachment/") . $filePath; // 绝对路径
  52. $fileFullName = $fileName . $fileExc; // 完整文件名
  53. if (!FileHelper::mkdirs($absolutePath)) {
  54. return ResultHelper::json(422, '文件夹创建失败,请确认是否开启attachment文件夹写入权限');
  55. }
  56. // 移动文件
  57. if (!$stream->save($absolutePath, $fileFullName)) {
  58. return ResultHelper::json(422, '文件移动失败');
  59. }
  60. return ResultHelper::json(200, '上传成功', [
  61. 'url' => $relativePath . $fileFullName
  62. ]);
  63. }
  64. }
粤ICP备19079148号