選擇圖片和上傳圖片

引言:在微信小程序中選擇手機圖片并上傳到后臺

主要步驟:

  • 使用wx.chooseImage來選擇圖片
  • 使用wx.uploadFile來上傳圖片

選擇圖片

<button bindtap='handleChooseAlbum' size="mini" >選擇圖片</button>
handleChooseAlbum(){
        //系統(tǒng)API,讓用戶在相冊中選擇圖片(或者拍照)
        wx.chooseImage({
            success : (res) => {
              //1、取出路徑
        const path = res.tempFilePaths
        console.log(res)

              //2、設(shè)置imagePath
              this.setData({
                imagePath : path
        })
            }
        })
  },

上傳圖片(多張)

uploadimg:function(shoper_id){
    var that = this
    for (var i = 0; i < that.data.imagePath.length; i++) {
      var imgUrl = that.data.imagePath[i];
      wx.uploadFile({
        //php 服務(wù)器地址
        url: config.url + 'shoper/saveimg',
        filePath: imgUrl,
        name: 'file',
        formData: {
          'shoper_id': shoper_id
        },
        success: function (res) {
          console.log("success");
        },
        fail: function (res) {
          console.log("error");
        }
      })
    }
  },

后臺

//存儲圖片
    public function saveimg()
    {
        //處理圖片
        $imgs = $_FILES['file'];
        $shoper_id = $_REQUEST['shoper_id'];

        if($imgs){
            $destination = $_SERVER['DOCUMENT_ROOT'].'/static/upload/images';
            //創(chuàng)建文件夾(按年月)
            $name = "/shoper/".date("Ym")."/";
            $ymname = $destination.$name;
            if(!is_dir($ymname)){
                mkdir($ymname,0777,true);
            }
            //文件名稱
            $filename = date("YmdHis",time()).'-'.substr(md5($imgs['name']),0,10).'.jpg';
            //存儲到文件夾,$imgs['tmp_name']是小程序端傳來的圖片臨時路徑
            move_uploaded_file($imgs['tmp_name'], $ymname.'/' . iconv("UTF-8", "gb2312", $filename));
            //存儲到數(shù)據(jù)庫
            $img_url = '/upload/images'.$name.$filename;
            $insert = [
                'filename' => $img_url,
                'shoper_id' => $shoper_id,
                'add_time' => time()
            ];
            Db::name('shoper_images')->insert($insert);
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容