小程序上传图片到七牛云(支持多张上传,预览,删除)
生活随笔
收集整理的這篇文章主要介紹了
小程序上传图片到七牛云(支持多张上传,预览,删除)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以下為wxml (使用的vant小程序ui框架,需在json文件里自行引入)
<view class='clearFloat'><view class='upload_title'>頭像展示(必填)<span class="basic_title_desc">(選一張好看的個人照片可以增加客戶點擊的機會哦)</span></view><view class='healthCertImg'><view class='imgrelative' wx:if="{{headIconArr}}" wx:for="{{headIconArr}}" wx:for-index="index" wx:for-item="item" wx:key="*this"><image class="image uploadimg" src="{{imgPath+item.key}}" mode="aspectFit" id="{{imgPath+item.key}}" catchtap='previewHeadIcon'>{{item}}</image><van-icon name="clear" custom-style="color:#979797;position:absolute;right:-20rpx;top:-20rpx;" id="{{index}}" bind:click="deleteHeadIcon" /></view><image src='../../imgs/upload.png' class='uploadimg upload_jkz' catchtap='headIcon' wx:if="{{IsHeadIcon}}"></image></view></view>以下為wxss
.clearFloat {clear: both;overflow: hidden; } .upload_title {color: #222;font-size: 32rpx;margin-bottom: 16rpx;display: block;margin-top: 50rpx; } .imgrelative {position: relative;height: 164rpx;width: 164rpx;margin-right: 43rpx;float: left; } .uploadimg {height: 164rpx;width: 164rpx;float: left; }以下為json
{"usingComponents": {"van-popup": "../../vant/popup/index","van-area": "../../vant/area/index","van-icon": "../../vant/icon/index","van-toast": "../../vant/toast/index","van-datetime-picker": "../../vant/datetime-picker/index","van-field": "../../vant/field/index","upload": "../../component/upload/index"} }以下為js文件(涉及到封裝的微信ajax和七牛云上傳圖片方法在下面)
const util = require('../../utils/util.js'); const qiniuUploader = require("../../utils/qiniuUploader");// 頭像展示上傳圖片headIcon() {var that = thisthat.chooesImage(that, 1, function(res) {that.data.headIconArr.push(res)// console.log(that.data.ysCertImgArr.length)if (that.data.headIconArr.length >= 1) {that.setData({IsHeadIcon: false});}that.setData({headIconArr: that.data.headIconArr});})},// 頭像展示預覽與刪除previewHeadIcon(e) {this._previewImage(e, this.data.headIconArr)},deleteHeadIcon(e) {var that = thisthat._deleteImage(e, that.data.headIconArr, function(files) {that.setData({headIconArr: files,IsHeadIcon: true});})},/*圖片上傳*/chooesImage(that, count, callback) {util.didPressChooesImage(that, count, function(filePath) {qiniuUploader.upload(filePath, (res) => {console.log(res)callback(res)that.checkSubmit()}, (error) => {console.error('error: ' + JSON.stringify(error));},null, // 可以使用上述參數,或者使用 null 作為參數占位符(progress) => {// console.log('上傳進度', progress.progress)// console.log('已經上傳的數據長度', progress.totalBytesSent)// console.log('預期需要上傳的數據總長度', progress.totalBytesExpectedToSend)}, cancelTask => that.setData({cancelTask}));})}, /*圖片預覽*/_previewImage: function(e, arr) {var preUlrs = [];console.log(arr)const imgPath = 'https://cdn.wutongdaojia.com/'arr.map(function(value, index) {var key = imgPath + value.keypreUlrs.push(key);});wx.previewImage({current: e.currentTarget.id, // 當前顯示圖片的http鏈接urls: preUlrs // 需要預覽的圖片http鏈接列表})},/*圖片刪除*/_deleteImage: function(e, arr, callback) {var that = this;var files = arr;var index = e.currentTarget.dataset.index; //獲取當前長按圖片下標console.log(index)wx.showModal({title: '提示',content: '確定要刪除此圖片嗎?',success: function(res) {if (res.confirm) {files.splice(index, 1);console.log(files)} else if (res.cancel) {return false;}// files,that.setData({isCanAddFile: true});that.checkSubmit()callback(files)}})},以下為封裝的七牛云上傳圖片方法(util.js)
const qiniuUploader = require("./qiniuUploader"); import api from './api.js';const getUploadToken = () => {var params = {token: wx.getStorageSync('token')}api.ajax("GET", params, "/weixin/getUploadToken").then(res => {console.log(res.data)initQiniu(res.data)}); } // 初始化七牛相關參數 const initQiniu = (uptoken) => {var options = {region: 'NCN', // 華北區// uptokenURL: 'https://[yourserver.com]/api/uptoken',// cdn.wutongdaojia.com// uptokenURL: 'http://upload-z1.qiniup.com',// uptokenURL: 'https://yuesao.wutongdaojia.com/weixin/getUploadToken',// uptoken: 'xxx',uptoken: uptoken,// domain: 'http://[yourBucketId].bkt.clouddn.com',domain: 'space.bkt.clouddn.com', // space為七牛云后臺創建的空間shouldUseQiniuFileName: false};qiniuUploader.init(options); }export function didPressChooesImage(that, count, callback) {getUploadToken();// 微信 API 選文件wx.chooseImage({count: count,success: function(res) {console.log(res)var filePath = res.tempFilePaths[0];console.log(filePath)callback(filePath)// 交給七牛上傳}}) }/*** 文件上傳* 服務器端上傳:http(s)://up.qiniup.com* 客戶端上傳: http(s)://upload.qiniup.com* cdn.wutongdaojia.com*/ function uploader(file, callback) {initQiniu();qiniuUploader.upload(filePath, (res) => {// 每個文件上傳成功后,處理相關的事情// 其中 info 是文件上傳成功后,服務端返回的json,形式如// {// "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",// "key": "gogopher.jpg"// }// 參考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.htmlthat.setData({'imageURL': res.imageURL,});}, (error) => {console.log('error: ' + error);},// , {// region: 'NCN', // 華北區// uptokenURL: 'https://[yourserver.com]/api/uptoken',// domain: 'http://[yourBucketId].bkt.clouddn.com',// shouldUseQiniuFileName: false// key: 'testKeyNameLSAKDKASJDHKAS'// uptokenURL: 'myServer.com/api/uptoken'// }null, // 可以使用上述參數,或者使用 null 作為參數占位符(res) => {console.log('上傳進度', res.progress)console.log('已經上傳的數據長度', res.totalBytesSent)console.log('預期需要上傳的數據總長度', res.totalBytesExpectedToSend)}); }; module.exports = {initQiniu: initQiniu,getUploadToken: getUploadToken,didPressChooesImage: didPressChooesImage }封裝小程序wx.request(api.js)
const ajax = (Type, params, url) => {var methonType = "application/json";// var https = "http://www.wutongdaojia.com"var https = "https://yuesao.wutongdaojia.com"var st = new Date().getTime()if (Type == "POST") {methonType = "application/x-www-form-urlencoded"}return new Promise(function (resolve, reject) {wx.request({url: https + url,method: Type,data: params,header: {'content-type': methonType,'Muses-Timestamp': st,'version': 'v1.0' // 版本號// 'Muses-Signature': sign},success: function (res) {// if (res.statusCode != 200) {// reject({ error: '服務器忙,請稍后重試', code: 500 });// return;// }// resolve(res.data);wx.hideLoading()console.log(res)if (res.data.status == 200) {resolve(res.data);} else if (res.data.status == 400) {wx.showToast({title: res.data.message,icon: 'none',duration: 1000})return} else if (res.data.status == 401){wx.removeStorageSync('phone')wx.removeStorageSync('token')wx.showToast({title: res.data.message,icon: 'none',duration: 1000,success:function(){wx.navigateTo({url: '../login/index',})}})return} else {//錯誤信息處理wx.showToast({title: '服務器錯誤,請聯系客服',icon: 'none',duration: 1000})}},fail: function (res) {// fail調用接口失敗reject({ error: '網絡錯誤', code: 0 });},complete: function (res) {// complete}})}) }有什么不懂的可以加我微信(18310911617)
備注(說明來意)
總結
以上是生活随笔為你收集整理的小程序上传图片到七牛云(支持多张上传,预览,删除)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: excel2010冻结行列
- 下一篇: WebRTC 及点对点网络通信机制