uni-app 上传base64图片

1、安装图片路径转base64js

新建plugin/image-tools/index.js

function getLocalFilePath(path) {
    if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
        return path
    }
    if (path.indexOf('file://') === 0) {
        return path
    }
    if (path.indexOf('/storage/emulated/0/') === 0) {
        return path
    }
    if (path.indexOf('/') === 0) {
        var localFilePath = plus.io.convertAbsoluteFileSystem(path)
        if (localFilePath !== path) {
            return localFilePath
        } else {
            path = path.substr(1)
        }
    }
    return '_www/' + path
}

export function pathToBase64(path) {
    return new Promise(function(resolve, reject) {
        if (typeof window === 'object' && 'document' in window) {
            if (typeof FileReader === 'function') {
                var xhr = new XMLHttpRequest()
                xhr.open('GET', path, true)
                xhr.responseType = 'blob'
                xhr.onload = function() {
                    if (this.status === 200) {
                        let fileReader = new FileReader()
                        fileReader.onload = function(e) {
                            resolve(e.target.result)
                        }
                        fileReader.onerror = reject
                        fileReader.readAsDataURL(this.response)
                    }
                }
                xhr.onerror = reject
                xhr.send()
                return
            }
            var canvas = document.createElement('canvas')
            var c2x = canvas.getContext('2d')
            var img = new Image
            img.onload = function() {
                canvas.width = img.width
                canvas.height = img.height
                c2x.drawImage(img, 0, 0)
                resolve(canvas.toDataURL())
                canvas.height = canvas.width = 0
            }
            img.onerror = reject
            img.src = path
            return
        }
        if (typeof plus === 'object') {
            plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
                entry.file(function(file) {
                    var fileReader = new plus.io.FileReader()
                    fileReader.onload = function(data) {
                        resolve(data.target.result)
                    }
                    fileReader.onerror = function(error) {
                        reject(error)
                    }
                    fileReader.readAsDataURL(file)
                }, function(error) {
                    reject(error)
                })
            }, function(error) {
                reject(error)
            })
            return
        }
        if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
            wx.getFileSystemManager().readFile({
                filePath: path,
                encoding: 'base64',
                success: function(res) {
                    resolve('data:image/png;base64,' + res.data)
                },
                fail: function(error) {
                    reject(error)
                }
            })
            return
        }
        reject(new Error('not support'))
    })
}

export function base64ToPath(base64) {
    return new Promise(function(resolve, reject) {
        if (typeof window === 'object' && 'document' in window) {
            base64 = base64.split(',')
            var type = base64[0].match(/:(.*?);/)[1]
            var str = atob(base64[1])
            var n = str.length
            var array = new Uint8Array(n)
            while (n--) {
                array[n] = str.charCodeAt(n)
            }
            return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
        }
        var extName = base64.match(/data\:\S+\/(\S+);/)
        if (extName) {
            extName = extName[1]
        } else {
            reject(new Error('base64 error'))
        }
        var fileName = Date.now() + '.' + extName
        if (typeof plus === 'object') {
            var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
            bitmap.loadBase64Data(base64, function() {
                var filePath = '_doc/uniapp_temp/' + fileName
                bitmap.save(filePath, {}, function() {
                    bitmap.clear()
                    resolve(filePath)
                }, function(error) {
                    bitmap.clear()
                    reject(error)
                })
            }, function(error) {
                bitmap.clear()
                reject(error)
            })
            return
        }
        if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
            var filePath = wx.env.USER_DATA_PATH + '/' + fileName
            wx.getFileSystemManager().writeFile({
                filePath: filePath,
                data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
                encoding: 'base64',
                success: function() {
                    resolve(filePath)
                },
                fail: function(error) {
                    reject(error)
                }
            })
            return
        }
        reject(new Error('not support'))
    })
}

2、新建util.js

 import {
 	pathToBase64
 } from '@/plugin/image-tools/index.js'
 
  export default {
	  
	  /*
	   * 单图上传base64
	   * @param object opt
	   * @param callable successCallback 成功执行方法 data 
	   * @param callable errorCallback 失败执行方法 
	   */
	  imageOneBase64: function(opt, successCallback, errorCallback) {
	  	let that = this;
	  	if (typeof opt === 'string') {
	  		opt = {};
	  	}
	  	let count = opt.count || 1,
	  		sizeType = opt.sizeType || ['compressed'],
	  		sourceType = opt.sourceType || ['album', 'camera'],
	  		is_load = opt.is_load || true,
	  		inputName = opt.name || 'pics',
	  		fileType = opt.fileType || 'image';
	  	uni.chooseImage({
	  		count: count, //最多可以选择的图片总数  
	  		sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有  
	  		sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有  
	  		success: function(res) {
	  			//启动上传等待中...  
	  			uni.showLoading({
	  				title: '图片上传中',
	  			});
	  			pathToBase64(res.tempFilePaths[0])
	  				.then(imgBase64 => {
	  					let newData = {
	  						tempFilePath: res.tempFilePaths[0],
	  						imgBase64: imgBase64,
	  					}
	  					uni.hideLoading();
	  					successCallback && successCallback(newData)
	  				})
	  				.catch(error => {
	  					errorCallback && errorCallback(error);
						uni.$showMsg(error.msg)
	  				})
	  		},
	  		fail: function(res) {
	  			uni.hideLoading();
	  		}
	  	})
	  },
	  /*
	   * 单图上传
	   * @param object opt
	   * @param callable successCallback 成功执行方法 data 
	   * @param callable errorCallback 失败执行方法 
	   */
	  uploadImageOne: function(opt, successCallback, errorCallback) {
	  	let that = this;
	  	if (typeof opt === 'string') {
	  		let url = opt;
	  		opt = {};
	  		opt.url = url;
	  	}
	  	let count = opt.count || 1,
	  		sizeType = opt.sizeType || ['compressed'],
	  		sourceType = opt.sourceType || ['album', 'camera'],
	  		is_load = opt.is_load || true,
	  		uploadUrl = opt.url || '',
	  		inputName = opt.name || 'pics',
	  		fileType = opt.fileType || 'image';
	  	uni.chooseImage({
	  		count: count, //最多可以选择的图片总数  
	  		sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有  
	  		sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有  
	  		success: function(res) {
	  			//启动上传等待中...  
	  			uni.showLoading({
	  				title: '图片上传中',
	  			});
	  			uni.uploadFile({
	  				url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
	  				filePath: res.tempFilePaths[0],
	  				fileType: fileType,
	  				name: inputName,
	  				formData: {
	  					'filename': inputName
	  				},
	  				header: {
	  					// #ifdef MP
	  					"Content-Type": "multipart/form-data",
	  					// #endif
	  					[TOKENNAME]: 'Bearer ' + store.state.app.token
	  				},
	  				success: function(res) {
	  					uni.hideLoading();
	  					if (res.statusCode == 403) {
	  						
							uni.$showMsg(res.data)
	  					} else {
	  						let data = res.data ? JSON.parse(res.data) : {};
	  						if (data.status == 200) {
	  							successCallback && successCallback(data)
	  						} else {
	  							errorCallback && errorCallback(data);
	  							
								uni.$showMsg(error.msg)
	  						}
	  					}
	  				},
	  				fail: function(res) {
	  					uni.hideLoading();
						uni.$showMsg('上传图片失败')
	  				}
	  			})
	  		
	  		}
	  	})
	  }
  }
  
  

3、

import util from './utils/util.js'

Vue.prototype.$util = util

4、图片子组件---点击上传图片

<template>
	<view>
		<!-- 循环图片 -->
		<view v-for="(item, index) in imgList" :key="index" :style="{width:width + 'rpx', height:height + 'rpx'}">
			<image class="img" :src="item"></image>
		</view>
		
		<!-- 添加图片的图标 -->
		<view class="share-img-box" :style="{width:width + 'rpx', height:height + 'rpx'}" v-if="imgList.length < maxCount">
			<image src="../../static/button/addimg.png" mode="" @click="addImg"></image>
		</view>
	</view>
</template>

<script>
	export default {
		name: "addImg",
		data() {
			return {
				// 图片数组
				imgList: [],
				// base64图片数组
				imgBase64List: [],
				indexNum: 0
			};
		},

		props: {
			width: {
				type: Number,
				default: 100
			},
			height: {
				type: Number,
				default: 100
			},
			maxCount:{
				type:Number,
				default:1
			}
		},
		methods: {
			addImg() {
				let _this = this
				let opt = {
					count: this.maxCount,
					sizeType: this.sizeType,
					sourceType: this.sourceType
				}
				// 从本地相册选择图片或使用相机拍照
				this.$util.imageOneBase64(opt, function(res) {
					_this.imgList.unshift(res.tempFilePath);
					// console.log(res)
					console.log(_this.imgList);
					_this.imgBase64List.unshift(res.imgBase64);
					let arr = {
						key: _this.indexNum,
						imgBase64: _this.imgBase64List
					}
					_this.$emit('imgListChange', arr)
				});
			},
		}
	}
</script>

<style lang="scss">
	.share-img-box {
		
		background: #f7f7f7;
		border-radius: 3px;
		display: flex;
		justify-content: center;
		align-items: center;

	}
	
	.img{
		width: 100%;
		height: 100%;
	}
</style>

5、父组件

<view class="select-vote" v-for="(item,index) in optionsList" :key="index">
					<view>
						<addImg width="100" height="100" @imgListChange="imgListChange" :indexNum="index"></addImg>
						<input class="input-box" type="text" v-model="item.name" :placeholder="'请输入活动标题' + (index +1) "  />
					</view>
					<image class="icon" src="../../static/button/clear.png"></image>
				</view>




// 投票选项
				optionsList:[
					{
						name:'',
						image:''
					}
				],

imgListChange(e){
				console.log(e)
				this.optionsList[e.key].image = e.imgBase64
			},

上一篇:uni.chooseLocation使用心得


下一篇:uniapp封装promise请求/上传图片等常用类