2021-02-24 laravel 接收小程序上传的文件

1.在控制器中添加调用方法

public function image(Request $request)
    {
        try {
            return response()->json(['code' => 200, 'url' => Upload::appletsImage()]);
        }catch (\Exception $exception) {
            return response()->json(['code' => 404, 'url' => $exception->getMessage()]);
        }
    }

2.在模型中添加保存文件的方法

public static function appletsImage()
    {
        $file = $_FILES['file'];
        $Path = "/images/" . date('Y-m-d') . "/withdraw/";
        if (!empty($file)) {

            $type = pathinfo($file['name'])['extension'];
            if (!in_array($type, ['jpg', 'png', 'gif'])) {
                throw new \Exception('不支持以外jpg和png还有gif的图片格式!');
            }

            $fileName = request()->server('DOCUMENT_ROOT') . '/storage' . $Path;//文件路径
            $upload_name = 'img_' . date("YmdHis") . rand(0, 100) . '.' . $type;//文件名加后缀
            if (!file_exists($fileName)) {
                //进行文件创建
                mkdir($fileName, 0777, true);
            }
            $imageSavePath = $fileName . $upload_name;
            if (move_uploaded_file($_FILES['file']['tmp_name'], $imageSavePath)) {
                return $Path . $upload_name;
            }
        }

        return null;
    }

3.小程序测试代码

chooseImage(tapIndex) {
      var checkeddata = true
      var that = this
      var domain = wx.getStorageSync('config')

      wx.chooseImage({
        //count表示一次可以选择多少照片
        count: 1,
        //sizeType所选的图片的尺寸,original原图,compressed压缩图
        sizeType: ['original', 'compressed'],
        //如果sourceType为camera则调用摄像头,为album时调用相册
        sourceType: [that.data.sourceType[tapIndex]],
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths
          //将选择到的图片缓存到本地storage中
          wx.uploadFile({
            url: 'http://fiveyears.cc/upload/image',
            filePath: tempFilePaths[0],
            name: 'file',
            success (res){
              var data = JSON.parse(res.data);
              console.log(data)
              wx.setStorageSync('tempFilePaths', data.url)
              wx.showToast({
                title: '选择成功',
                icon: 'success',
                duration: 2000
              })
            }
          })
          /*
      由于在我们选择图片后图片只是保存到storage中,所以我们需要调用一次              setHeader()方法来使页面上的头像更新
      */
          that.setHeader();
        }
      })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值