1. 程式人生 > 程式設計 >微信小程式實現多圖上傳

微信小程式實現多圖上傳

本文例項為大家分享了微信小程式實現多圖上傳的具體程式碼,供大家參考,具體內容如下

前言

純屬是筆記,複用性太高,前後端封裝的上傳的多圖方法

看一下效果圖

微信小程式實現多圖上傳

index.html

<view class="imgs">
  <block wx:for="{{ imgs }}" wx:key="{{ index }}">
   <view class="img-box">
    <image src="{{ item }}" />
    <icon class="iconfont" size='18px' color="gray" data-index='{{ index }}' bind:tap="close" type='cancel'></icon>
   </view>
   </block>
 <image bind:tap="uploadImg" class="add" src="./upload.png" />
</view>

index.css

/* 上傳照片 */

.imgs {
 margin-top: 20rpx;
 display: flex;
 flex-wrap: wrap;
}

.img-box {
 width: 100rpx;
 height: 100rpx;
 margin: 0 10rpx;
 flex-shink: 0;
 position: relative;
 margin-bottom: 10rpx;
}

.img-box .iconfont {
 position: absolute;
 top: -10rpx;
 right: 3rpx;
 font-size: 16rpx;
 width: 20rpx;
 height: 20rpx;
 line-height: 30rpx;
 text-align: center;
 border-radius: 50%;
 color: #fff;
}

.imgs image {
 width: 100rpx;
 height: 100rpx;
}

.add {
 margin-left: 10rpx;
}

util.js封裝上傳照片的方法

var app = getApp()

// const host = "http://www.qd1.com"
// const host = "http://192.168.1.200"
// const host = "https://work.zez.cn"
// const host = "http://192.168.1.151"
// const host = "http://192.168.1.9.8083"
// const host ="http://192.168.1.244"
const host = "http://192.168.10.9:8085"//郭

const formatTime = () => {
 const date = new Date()
 const year = date.getFullYear()
 const month = date.getMonth() + 1
 const day = date.getDate()
 const hour = date.getHours()
 const minute = date.getMinutes()
 return [year,month,day].map(formatNumber).join('-') + ' ' + [hour,minute].map(formatNumber).join(':')
}


const formatNumber = n => {
 n = n.toString()
 return n[1] ? n : '0' + n
}
function pxToRpx(px) {
 const systemInfo = wx.getSystemInfoSync()
 return px / systemInfo.windowWidth * 750
}

function rpxToPx(rpx) {
 const systemInfo = wx.getSystemInfoSync()
 return rpx / 750 * systemInfo.windowWidth
}

function isBlank(str) {
 //判斷物件是否為空值
 if (Object.prototype.toString.call(str) === '[object Undefined]') { //空
 return true
 } else if (
 Object.prototype.toString.call(str) === '[object String]' ||
 Object.prototype.toString.call(str) === '[object Array]') { //字條串或陣列
 return str.length == 0 ? true : false
 } else if (Object.prototype.toString.call(str) === '[object Object]') {
 return JSON.stringify(str) == '{}' ? true : false
 } else {
 return true
 }

}

**//上傳圖片    //遞迴上傳
function uploadImage(url,filePaths,i = 0,callback) {
 const length = filePaths.length
 wx.showLoading({
 title: '上傳中..',mask: true
 })
 wx.uploadFile({
 header: app.globalData.header,url: host + url,filePath: filePaths[i],name: 'file',success: res => {
  callback && callback(res)
  i++  
  if (i < length) {
  this.uploadImage(url,i,callback)
  } else {
  wx.hideLoading()
  wx.showToast({
   title: '上傳完成!',})
  }
 },fail: res => {
  callback && callback(res)
  wx.hideLoading()
  wx.showToast({
  title: '上傳失敗!',icon: 'none'
  })
 }
 })
}**


//生成隨機字串
function generateMixed(n) {
 var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G']
 var res = "";
 for (var i = 0; i < n; i++) {
 var id = Math.round(Math.random() * (chars.length - 1));
 res += chars[id];
 }
 return res;
}

// 開啟地圖選擇器
var getPosition = (that) => {
 wx.chooseLocation({
 success: (res) => {
  var newAddress = {
  addressName: res.name,address: res.address,latitude: res.latitude,//緯度
  longitude: res.longitude //經度 
  }
  that.data.addresses.unshift(newAddress)
  that.setData({
  addresses: that.data.addresses,chooseLocation: true
  })
  wx.showToast({
  title: '新增成功',icon: 'success'
  })
 }
 })
}

function userInfo() {
 //獲取使用者資訊儲存到全域性變數
 return new Promise((resolve,failed) => wx.getUserInfo({
 success: res => {
  app.globalData.userInfo = res.userInfo,resolve(res)
 },fail: err => {
  wx.showToast({
  title: '網路錯誤',icon: 'none'
  }),failed()
 }
 }))
}

function login() {
 return new Promise((resolve,failed) => wx.login({
 success: res => {
  app.globalData.header = {
  "Content-Type": "application/x-www-form-urlencoded","Cookie": 'code=' + res.code,},failed()
 }

 }))
}

/**
 * [checkPhone 驗證手機號]
 * @Author tomorrow-here
 * @DateTime 2018-12-20
 * @param {string}  phone [要驗證的手機號字串]
 * @return {boolean}   [手機號正確,返回true,否則返回false]
 */
function checkPhone(phone) {
 if (!(/^1[34578]\d{9}$/.test(phone))) {
 wx.showToast({
  title: '請輸入正確的手機號!',icon: 'none'
 })
 return false
 } else {
 return true
 }
}


module.exports = {
 formatTime,getPosition,post,get,login,isBlank,userInfo,generateMixed,uploadImage,pxToRpx,rpxToPx,checkPhone
}

index.js

import {
 uploadImg
} from '../../utils/util.js';
const tool = require("../../utils/util.js")
pages({
data:{
imgs:[],imgsArr:[],//裝後臺要的資料格式
}
 //多圖 圖片上傳
 uploadImg() {
 wx.chooseImage({
  success: res => {
  tool.uploadImage("/returnFileInfo",res.tempFilePaths,(res) => {
   var imgsrc = {
   src: JSON.parse(res.data).path,//後臺返回的事json格式,需要轉換
   relateType: 2}
   this.data.imgsArr.push(imgsrc)
   this.setData({
   imgsArr: this.data.imgsArr
   },() => {
   console.log(this.data.imgsArr,'|imgsrc')
   })
  })
  this.setData({
   imgs: [...this.data.imgs,...res.tempFilePaths]
  })
  }
 })
 },/** 
 * @Author: tomorrow-here 
 * @Date: 2019-1-22
 * @Desc: 刪除圖片 
 */
 close(e) {
 const index = e.currentTarget.dataset.index
 this.data.imgs.splice(index,1)
 this.setData({
  imgs: this.data.imgs
 })
 },})

為大家推薦現在關注度比較高的微信小程式教程一篇:《微信小程式開發教程》小編為大家精心整理的,希望喜歡。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。