..._微信小程序上传图片时不需要调接口吗,上传完了以后只需要调一个保存的接口">
当前位置:   article > 正文

小程序——图片上传预览及后台接口存储_微信小程序上传图片时不需要调接口吗,上传完了以后只需要调一个保存的接口

微信小程序上传图片时不需要调接口吗,上传完了以后只需要调一个保存的接口

首先是,选择图片预览删除的wxml文件

<view class='top-selected_1'>
      <view class="cross_column">
        <view class="cross_column">
          <block wx:for="{{images}}" wx:key="*this">
            <view>
              <!-- 图片缩略图  -->
              <image class="imgcls_4" src="{{item}}" mode="aspectFill" data-idx="{{index}}" bindtap="ImagePreview"></image>
              <!-- 移除图片的按钮  -->
              <view style=" text-align: center;" data-idx="{{index}}" bindtap="removeImage">删除</view>
            </view>
          </block>
        </view>
        <image class="imgcls_4" bindtap="chooseImg" wx:if="{{images.length < 4}}" src="../image/add.png"></image>
      </view>
    </view>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

.js文件,注意这里要引用.util文件

链接:https://pan.baidu.com/s/1ytn5aZDqs4MYs1cV1C7hAg
提取码:k7r3

    import {
      $init,
      $digest
    } from '../../utils/common.util'
    Page({
        images: []
      },
    
  //上传图片
  chooseImg: function(e) {
    var that = this;
    var images = that.data.images;
    //wx.chooseImage函数就是用来访问手机相册或摄像头的。
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        for (var i = 0; i < tempFilePaths.length; i++) images.push(tempFilePaths[i]);
        // 限制最多只能留下4张照片
        this.data.images = images.length <= 4 ? images : images.slice(0, 4)
        console.log(images);
        $digest(this) //等同于this.setData
      }
    });
  },
  //移除图片
  removeImage(e) {
    const idx = e.target.dataset.idx
    this.data.images.splice(idx, 1) //删除idx后一张图片
    $digest(this)
  },
  //图片预览
  ImagePreview(e) {
    const idx = e.target.dataset.idx
    const images = this.data.images
    //wx.previewImage预览图片的函数,可以对预览图片进行左右滑动
    wx.previewImage({
      current: images[idx], //当前预览的图片
      urls: images, //所有要预览的图片
    })
  },
  
  onLoad: function(options) {
    $init(this);
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

添加上传图片的按钮

  <button bindtap='chooseImageTap'>上传图片</button>
  • 1

js方法的编写

  //添加上传图片
  chooseImageTap: function() {
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#00000",
      success: function(res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera')
          }
        }
      }
    })
  },
  // 图片本地路径
  chooseWxImage: function(type) {
    var that = this;
    var imgsPaths = that.data.imgs;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function(res) {
        console.log(res.tempFilePaths[0]);
        that.upImgs(res.tempFilePaths[0], 0) //调用上传方法
      }
    })
  },
  //上传服务器
  upImgs: function(imgurl, index) {
    var that = this;
    wx.uploadFile({
      url: '*******************/Upload', //你接口的地址
      filePath: imgurl,
      name: 'file',
      header: {
        'content-type': 'appication/x-www-form-urlencoded'
      },
      formData: null,
      success: function(res) {
        console.log(res.data)
      }
    })
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

后台接口代码,根据自己的本地存储地址修改相应的代码

/// <summary>
        /// 小程序图片上传
        /// </summary>
        [WebMethod(EnableSession = true)]
        public void Upload()
        {
            //获取文件路径
            HttpFileCollection files = HttpContext.Current.Request.Files;
            //返回的对象初始化
            object obj = null;
            //获取项目路径
            string sPath = System.Web.HttpContext.Current.Request.PhysicalPath;
            //得到上一级路径
            DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}..\..\", sPath));
            string sFilePath = Path.Combine(di.FullName, "Upload", DateTime.Today.Year.ToString(), DateTime.Today.Month.ToString(), DateTime.Today.Day.ToString(), "");
            //不存在路径则创建该路径
            if (!Directory.Exists(sFilePath))
            {
                Directory.CreateDirectory(sFilePath);
            }
            foreach (string key in files.AllKeys)
            {
                HttpPostedFile file = files[key];//file.ContentLength文件长度
                if (string.IsNullOrEmpty(file.FileName) == false)
                {
                    string fileName = Path.GetFileName(file.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    string saveName = Guid.NewGuid().ToString() + fileExtension; // 保存文件名称
                    string fileSaveAsName = string.Format(@"{0}\{1}", sFilePath, saveName);//保存文件路径
                    file.SaveAs(fileSaveAsName);//保存
                    string sUrl = Path.Combine("Upload", DateTime.Today.Year.ToString(), DateTime.Today.Month.ToString(), DateTime.Today.Day.ToString(), saveName);//Url地址
                    obj = (new { resultCode = "001", FileName = saveName, Url = "http://localhost:14146/" + sUrl });
                }
                else obj = (new { resultCode = "003", Message = "请选择要上传的文件!" });
            }
            HttpContext.Current.Response.Write(obj);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签