以下為wxml
<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>
以下為js
const util = require('../../utils/util.js'); const qiniuUploader = require("../../utils/qiniuUploader"); // 頭像展示上傳圖片 headIcon() { var that = this that.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 = this that._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.key preUlrs.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: 'image.bkt.clouddn.com', // image為七牛雲后台創建的空間 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.html that.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 }
封裝ajax(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 } }) }) }