欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

微信小程序上传图片,PHP-Laravel框架实现 有大用

流程概述:

利用微信小程序自带的wx.uploadFile方法,将文件post 到服务器API接口,接受内容,保存

文档地址
https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-file.html

image.png
image.png

为什么实例里边没有将 content-type 为 multipart/form-data 放进去呢,想不懂

image.png
image.png

直接上代码

js 文件
/选择上传图片
bindUploadTap:function(){
  let that = this
  wx.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths
      
      
      that.setData({
        imgsrc: tempFilePaths[0]
      })

      wx.uploadFile({
        header: {
          'content-type': 'multipart/form-data'
        },
        url: 'https://www.com/api/v1/Index/upload_img', //仅为示例,非真实的接口地址
        filePath: tempFilePaths[0],
        name: 'logo',
        formData: {
          'user': 'test'
        },
        success: function (res) {
          var data = res.data
          console.log(res)
          //do something
        }
      })
    }
  })
},
wxml
<button size="mini" bindtap="bindUploadTap">
选择图片
</button>
<image src="{{imgsrc}}"></image>

Laravel 控制器代码
/*
     * 上传图片测试
     */
    public function upload_img(Request $request)
    {

        if(!empty($_FILES['logo'])){
            Log::info($_FILES["logo"]["type"]."---".$_FILES["logo"]["name"]."---".$_FILES["logo"]["size"]);

            $uploaddir = 'app/public/uploads/';
            $uploadfile = $uploaddir . basename($_FILES['logo']['name']);
            Log::info($uploadfile);
            if (move_uploaded_file($_FILES['logo']['tmp_name'], storage_path($uploadfile))) {
                Log::info( "File is valid, and was successfully uploaded.\n");
            } else {
                Log::info(  "Possible file upload attack!\n");
            }


        }


        $ret['err']     = 0;
        $ret['msg']     = '成功';

        return response()->json($ret, $this->successStatus);

    }
效果图
image.png
image.png
image.png
image.png
日志
[2017-08-11 02:27:35] local.INFO: image/jpeg---tmp_434479379o6zAJs7WmNGKeKBJtiDmL7hpsGkw546260158a109feb82ba9d97a6b18942.jpg---35955  
[2017-08-11 02:27:35] local.INFO: app/public/uploads/tmp_434479379o6zAJs7WmNGKeKBJtiDmL7hpsGkw546260158a109feb82ba9d97a6b18942.jpg  
[2017-08-11 02:27:35] local.INFO: File is valid, and was successfully uploaded.
image.png
image.png

说明上传成功啦。

本文来自:简书

感谢作者:浪来了2016

查看原文:微信小程序上传图片,PHP-Laravel框架实现

72 次点击  
加入收藏 微博 
 

普通分类: