**微信小程序图片上传+后台PHP修改图片名称**

微信小程序图片上传+后台PHP修改图片名称

前端代码:比较随意
<view class="weui-uploader">
  <view class="img-v weui-uploader__bd">
    <view class='pic' wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
        <image class='weui-uploader__img '
                src="{{item}}"
                data-index="{{index}}" mode="aspectFill" bindtap="previewImg">
                  <icon type='cancel' class="delete-btn" data-index="{{index}}" catchtap="deleteImg"></icon>
        </image>
    </view>
     
      <!-- 用来提示用户上传图片 -->
      <view class="weui-uploader__input-box pic" bindtap="chooseImg"> </view>
  </view>
  <button class="upload-img-btn" bindtap="chooseImg" type='primary'>拍照  / 上传</button>
  <button bindtap="upImgs">上传</button>
</view>
// An highlighted block
小程序js代码:
chooseImg: function (e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 9) {
      this.setData({
        lenMore: 1
      });
      setTimeout(function () {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    wx.chooseImage({
      // count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        // console.log(tempFilePaths + '----');
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length >= 9) {
            that.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
          }
        }
        console.log(imgs);
        that.setData({
          imgs: imgs
        });
      }
    });
  },
  // 删除图片
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  // 预览图片
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },
  upImgs: function () {
    console.log(this.data.imgs[0]);
    var that = this;
    wx.uploadFile({
      url: 'https://xxxxxxxx/upload',//自己的后台接口路径
      filePath: this.data.imgs[0],
      name: 'file',
      header: {
        'content-type': 'multipart/form-data'
      },
      formData: null,
      success: function (res) {
        console.log(res) //接口返回网络路径
        // var data = JSON.parse(res.data)
        // that.data.picPaths.push(data['msg'])
        // that.setData({
        //   picPaths: that.data.picPaths
        // })
        // console.log(that.data.picPaths)
      }
    })
  },
  php后台代码:
  public function up_image (){
        $upload_dir = $_SERVER['DOCUMENT_ROOT'].'/images/';//首先获取当前文件的根目录,然后再拼接上存储图片目录
        $file=$_FILES['file'];//获取小程序上传的图片
        $file_name = $file['name'];//获取图片名称
        $temp_name=$file['tmp_name'];
        $arr = explode('.',$file_name);//首先根据'.'分隔文件名,然后用end($arr)来获取最后一个 就是图片类型
        $filename ="/". '.' . end($arr);//这里输出格式:/.jpg
        $fileName = str_replace(".", time() . ".", $filename);//在图片名称中加入时间戳
       //移动临时文件夹中的文件1到存放上传文件的目录,并重命名为真实名称
        if (move_uploaded_file($temp_name, $upload_dir . $fileName)) {
            echo "上传文件成功!";
        } else {
            echo "上传文件失败";
        }
        return $fileName;
    }

}

目前就这么多,花了好久总结的,自己遇到的坑,记录下,大家有需要可以参考参考

你可能感兴趣的:(小程序,小程序)