微信小程序实现多图上传


Posted in Javascript onJune 19, 2020

本文实例为大家分享了微信小程序实现多图上传的具体代码,供大家参考,具体内容如下

前言

纯属是笔记,复用性太高,前后端封装的上传的多图方法

看一下效果图

微信小程序实现多图上传

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.xxx.com"
// const host = "http://192.168.1.200"
// const host = "https://work.xxx.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, filePaths, 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,
 },
 resolve(res)
 },
 fail: err => {
 wx.showToast({
 title: '网络错误',
 icon: 'none'
 }),
 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, 0, (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
 })
 },
 })

为大家推荐现在关注度比较高的微信小程序教程一篇:《微信小程序开发教程》小编为大家精心整理的,希望喜欢。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
用javascript将数据库中的TEXT类型数据动态赋值到TEXTAREA中
Apr 20 Javascript
javascript json 新手入门文档
Dec 03 Javascript
JavaScript 验证码的实例代码(附效果图)
Mar 22 Javascript
页面图片浮动左右滑动效果的简单实现案例
Feb 10 Javascript
jquery选择checked在ie8普通模式下的问题
Feb 12 Javascript
JavaScript编程的10个实用小技巧
Apr 18 Javascript
JS中用三种方式实现导航菜单中的二级下拉菜单
Oct 31 Javascript
AngularJS实现Input格式化的方法
Nov 07 Javascript
js使用原型对象(prototype)需要注意的地方
Aug 28 Javascript
vue父组件异步获取数据传给子组件的方法
Jul 26 Javascript
JS实现求5的阶乘示例
Jan 21 Javascript
vue项目里面引用svg文件并给svg里面的元素赋值
Aug 17 Javascript
小程序表单认证布局及验证详解
Jun 19 #Javascript
小程序实现背景音乐播放和暂停
Jun 19 #Javascript
小程序选项卡以及swiper套用(跨页面)
Jun 19 #Javascript
如何配置vue.config.js 处理static文件夹下的静态文件
Jun 19 #Javascript
小程序实现多个选项卡切换
Jun 19 #Javascript
微信小程序 button样式设置为图片的方法
Jun 19 #Javascript
微信小程序之导航滑块视图容器功能的实现代码(简单两步)
Jun 19 #Javascript
You might like
UCenter中的一个可逆加密函数authcode函数代码
2010/07/20 PHP
PHP登录验证码的实现与使用方法
2016/07/07 PHP
PHP中时间加减函数strtotime用法分析
2017/04/26 PHP
利用PHP获取访客IP、地区位置、浏览器及来源页面等信息
2017/06/27 PHP
Laravel学习教程之request validation的编写
2017/10/25 PHP
ext checkboxgroup 回填数据解决
2009/08/21 Javascript
基于JQuery实现滚动到页面底端时自动加载更多信息
2014/01/31 Javascript
JavaScript中统计Textarea字数并提示还能输入的字符
2014/06/10 Javascript
深入探寻javascript定时器
2015/01/02 Javascript
jQuery实现form表单基于ajax无刷新提交方法详解
2015/12/08 Javascript
JQuery EasyUI学习教程之datagrid 添加、修改、删除操作
2016/07/09 Javascript
jQuery加密密码到cookie的实现代码
2017/04/18 jQuery
详解从Vue.js源码看异步更新DOM策略及nextTick
2017/10/11 Javascript
AngularJs 禁止模板缓存的方法
2017/11/28 Javascript
Thinkjs3新手入门之添加一个新的页面
2017/12/06 Javascript
基于webpack-hot-middleware热加载相关错误的解决方法
2018/02/22 Javascript
详解使用create-react-app快速构建React开发环境
2018/05/16 Javascript
VueCli3构建TS项目的方法步骤
2018/11/07 Javascript
Vue实现渲染数据后控制滚动条位置(推荐)
2019/12/09 Javascript
原生javascript制作贪吃蛇小游戏的方法分析
2020/02/26 Javascript
python使用7z解压apk包的方法
2015/04/18 Python
Python获取Redis所有Key以及内容的方法
2019/02/19 Python
Django url,从一个页面调到另个页面的方法
2019/08/21 Python
自适应线性神经网络Adaline的python实现详解
2019/09/30 Python
Python 统计位数为偶数的数字代码详解
2020/03/15 Python
Pymysql实现往表中插入数据过程解析
2020/06/02 Python
如何基于Python实现word文档重新排版
2020/09/29 Python
css3圆角样式分享自定义按钮样式
2013/12/27 HTML / CSS
Tirendo比利时:在线购买轮胎
2018/10/22 全球购物
英国儿童鞋和靴子:Start-Rite
2019/05/06 全球购物
给排水专业应届生求职信
2013/10/12 职场文书
技术副厂长岗位职责
2013/12/26 职场文书
公积金转移接收函
2014/01/11 职场文书
教师年度考核自我鉴定
2014/01/19 职场文书
企业标语口号
2014/06/10 职场文书
我在伊朗长大观后感
2015/06/16 职场文书