微信小程序-上传图片至阿里云

背景:最近有做这种需求,闲暇之余记录下,文章的内容有参考别人的代码,找不到链接了,就不放了
效果图如下展示:
在这里插入图片描述
html代码:

<!-- 容器 -->
<view class='ui_uploader_cell'>
    <!-- 根据已选择的图片临时路径数组展示图片-->
    <view class='ui_uploader_item' wx:for="{{uploaderList}}" wx:key="index">
        <!-- 删除-->
        <icon class='ui_uploader_item_icon' bindtap='clearImg' data-index="{{index}}" type="clear" size="20" color="red"/>
        <!-- 图片-->
        <image bindtap='showImg' data-index="{{index}}" src='{{item}}'></image>
    </view>
    <!-- 上传按钮+框 -->
    <view class='ui_uploader' bindtap='upload' wx:if="{{showUpload}}"></view>
</view>

js代码

//上传图片
		data: {
        	uploaderList: [],
        	tempFilePaths:null,
        	uploaderNum: 0,
        	showUpload: true,
        	fileUrlList: [],
     },
    upload: function(e) {
        var that = this;
        // 小程序自带方法,选择本地图片
        wx.chooseImage({
            count: 4 - that.data.uploaderNum, // 默认4
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function(res) {
                console.log(res)
                that.setData({
                    tempFilePaths:res.tempFilePaths[0]
                })
                // 获取上传策略
                axios({
                    url:'/file/getFileUploadPolicy',
                    method:'POST',
                    data:{
                        Token:wx.getStorageSync('token')
                    }
                }).then(res =>{
                    const data = res.data.data
                    // let timestamp = (new Date()).valueOf();  
                    // const fileName = that.data.tempFilePaths.substring(that.data.tempFilePaths.length - 20)
                    const  suffix = that.data.tempFilePaths.substring(that.data.tempFilePaths.length - 4) // 图片后缀名
                    const fileName = utils.randomTenNum(10) +suffix //文件名:十位随机数加后缀名(.jpg)
                    wx.uploadFile({ //上传到阿里云
                        url: data.host, 
                        filePath: tempFilePaths[0],
                        name: 'file',
                        formData: {
                            OSSAccessKeyId: data.accessid,
                            policy: data.policy,
                            signature: data.signature,
                            key: data.dir+'/'+fileName,
                            success_action_status:"200"
                          },
                        success (res){
                            that.data.fileUrlList.push(data.dir+'/'+fileName)
                            that.setData({
                                fileUrlList: that.data.fileUrlList
                            })
                        }
                      })
                })
                // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
                let tempFilePaths = res.tempFilePaths;
                let uploaderList = that.data.uploaderList.concat(tempFilePaths);
                if (uploaderList.length==4){
                    that.setData({
                        showUpload:false
                    })
                }
                that.setData({
                    uploaderList: uploaderList,
                    uploaderNum: uploaderList.length,
                })
            }
        })
    },
        // 删除图片
    clearImg:function(e){
        const fileUrlList = this.data.fileUrlList
        const index = e.currentTarget.dataset.index
        fileUrlList[index] = ''
        this.setData({
            fileUrlList:fileUrlList
        })
        var nowList = [];//新数据
        var uploaderList = this.data.uploaderList;//原数据
        
        for (let i = 0; i < uploaderList.length;i++){
            if (i == e.currentTarget.dataset.index){
                continue;
            }else{
                nowList.push(uploaderList[i])
            }
        }
        this.setData({
            uploaderNum: this.data.uploaderNum - 1,
            uploaderList: nowList,
            showUpload: true
        })
    },
    //展示图片
    showImg:function(e){
        var that=this;
        wx.previewImage({
            urls: that.data.uploaderList,
            current: that.data.uploaderList[e.currentTarget.dataset.index]
        })
    }

css样式

.ui_uploader_cell {
  width: 100%;
  /* padding: 40rpx; */
  padding-top: 16rpx;
  box-sizing: border-box;
}
.ui_uploader_item{
  float: left;
  position: relative;
  margin-right: 30rpx;
  margin-bottom: 30rpx;
  width: 120rpx;
  height: 120rpx;
}
.ui_uploader {
  float: left;
  position: relative;
  margin-right: 25rpx;
  margin-bottom: 25rpx;
  width: 120rpx;
  height: 120rpx;
  border: 2rpx solid #d9d9d9;
  box-sizing: border-box;
}

.ui_uploader:before {
  content: " ";
  position: absolute;
  width: 4rpx;
  height: 79rpx;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background-color: #d9d9d9;
}

.ui_uploader:after {
  content: " ";
  position: absolute;
  height: 4rpx;
  width: 79rpx;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background-color: #d9d9d9;
}
.ui_uploader_item_icon{
  position: absolute;
  right: -20rpx;
  top: -20rpx;
  background: #fff;
  border-radius: 50%;
}
.ui_uploader_item image {
  width: 100%;
  height: 100%;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的微信小程序中图片上传到阿里云OSS的例子: 1. 在微信小程序中,使用wx.chooseImage()方法选择需要上传的图片,并将其保存在本地变量tempFilePaths中。 ``` wx.chooseImage({ success: function(res) { var tempFilePaths = res.tempFilePaths; // 上传图片阿里云OSS uploadImage(tempFilePaths[0]); } }) ``` 2. 编写上传图片的函数uploadImage(),其中需要设置header、formData、name、url等参数,并调用wx.uploadFile()方法上传图片。 ``` function uploadImage(filePath) { // 阿里云OSS的Bucket名称和上传文件夹名称 var bucketName = 'your-bucket-name'; var folderName = 'your-folder-name/'; // 生成上传文件的唯一key var timestamp = new Date().getTime(); var key = folderName + timestamp + '-' + Math.floor(Math.random() * 10000) + '.jpg'; // 生成OSS的上传接口地址 var policyBase64 = 'your-policy-base64'; var signature = 'your-signature'; var aliyunUrl = 'https://' + bucketName + '.oss-cn-hangzhou.aliyuncs.com'; // 设置header和formData var header = { 'content-type': 'multipart/form-data' }; var formData = { 'key': key, 'policy': policyBase64, 'OSSAccessKeyId': 'your-access-key-id', 'success_action_status': '200', 'signature': signature }; // 调用wx.uploadFile()方法上传图片 wx.uploadFile({ url: aliyunUrl, filePath: filePath, name: 'file', header: header, formData: formData, success: function(res) { // 上传成功,获取图片URL地址 var imageUrl = aliyunUrl + '/' + key; console.log('上传成功,图片URL地址为:' + imageUrl); }, fail: function(res) { // 上传失败 console.log('上传失败:' + res.errMsg); } }) } ``` 需要注意的是,以上代码仅为一个示例,实际使用时需要按照阿里云OSS的规定进行设置,并在后端服务中编写相应的签名验证逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值