1、调用相机或相册上传图片
uni.chooseImage({
count: 1, // 最多可以选择的图片张数
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera','album'], // camera调用相机拍照,album是打开手机相册
success: (res)=> {
console.log(JSON.stringify(res.tempFilePaths));
}
})
2、图片文件转base64
(1)下载插件文章来源:https://www.toymoban.com/news/detail-511601.html
npm i image-tools --save
(2)页面引入插件 文章来源地址https://www.toymoban.com/news/detail-511601.html
<template>
<view class="container">
<view class="upload">
<view class="img-box" v-if="form.visitorPicture">
<image :src="form.visitorPicture" @click="handlePreview" mode="aspectFill"></image>
<uni-icons type="clear" class="clear" @click="form.visitorPicture = ''"></uni-icons>
</view>
<uni-icons type="plusempty" class="upload-box" @click="handleUpload" v-else></uni-icons>
</view>
<uni-icons type="right"></uni-icons>
</view>
</template>
<script>
import MyToast from './components/myToast.vue'
export default {
name: 'info',
data() {
return {
form: {
visitorPicture: ""
}
}
},
methods: {
// 上传头像
handleUpload() {
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['camera', 'album'],
success: (res) => {
uni.showLoading({
title: '图片上传中'
});
if(res.tempFilePaths[0].split(".")[1] === "jpg" || res.tempFilePaths[0].split(".")[1] === "JPG") {
if(res.tempFiles[0].size <= 10 * 1024 * 1024) {
// 图片转为base64
pathToBase64(res.tempFilePaths[0]).then(path => {
this.getImageUrl(path);
}).catch(error => {
uni.hideLoading();
})
} else {
uni.hideLoading();
this.errorToast = "请上传小于10MB的图片";
this.$refs.myToast.show();
}
} else {
uni.hideLoading();
this.errorToast = "请上传jpg格式的图片";
this.$refs.myToast.show();
}
}
});
},
// 获取上传到服务器图片的在线地址
getImageUrl(path) {
// todo 调用接口上传base64图片到后端
},
// 图片预览
handlePreview() {
uni.previewImage({
current: 0,
urls: [this.form.visitorPicture]
})
}
}
}
</script>
<style lang="less" scoped>
.upload {
width: 100rpx;
height: 100rpx;
position: relative;
.upload-box {
width: 100% !important;
height: 100%;
margin-left: 0 !important;
justify-content: center;
border: 2rpx #DDDDDD solid;
border-radius: 4rpx;
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
/deep/ .uniui-plusempty {
width: 100%;
height: 100%;
line-height: 96rpx;
text-align: center;
font-size: 40rpx !important;
color: #CCCCCC !important;
}
}
.img-box {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
image {
width: 100%;
height: 100%;
border-radius: 4rpx;
}
.clear {
width: 32rpx;
height: 32rpx;
position: absolute;
right: 0;
top: 0;
/deep/ .uniui-clear {
color: #7F7F7F !important;
font-size: 32rpx !important;
}
}
}
}
</style>
3、image-tools/index.js源码
function dataUrlToBase64(str) {
var array = str.split(',')
return array[array.length - 1]
}
var index = 0
function getNewFileId() {
return Date.now() + String(index++)
}
function biggerThan(v1, v2) {
var v1Array = v1.split('.')
var v2Array = v2.split('.')
var update = false
for (var index = 0; index < v2Array.length; index++) {
var diff = v1Array[index] - v2Array[index]
if (diff !== 0) {
update = diff > 0
break
}
}
return update
}
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.split(',')[0].match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
var fileName = getNewFileId() + '.' + extName
if (typeof plus === 'object') {
var basePath = '_doc'
var dirPath = 'uniapp_temp'
var filePath = basePath + '/' + dirPath + '/' + fileName
if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
plus.io.resolveLocalFileSystemURL(basePath, function(entry) {
entry.getDirectory(dirPath, {
create: true,
exclusive: false,
}, function(entry) {
entry.getFile(fileName, {
create: true,
exclusive: false,
}, function(entry) {
entry.createWriter(function(writer) {
writer.onwrite = function() {
resolve(filePath)
}
writer.onerror = reject
writer.seek(0)
writer.writeAsBinary(dataUrlToBase64(base64))
}, reject)
}, reject)
}, reject)
}, reject)
return
}
var bitmap = new plus.nativeObj.Bitmap(fileName)
bitmap.loadBase64Data(base64, function() {
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: dataUrlToBase64(base64),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
到了这里,关于uni-app 调用相机或相册图片并转为base64格式上传图片的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!