赞
踩
【1】导入uni-file-picker插件
【2】template
<view class="example-body">
<uni-file-picker title="上传营业执照" limit="3" fileMediatype="image" mode="grid"
v-model="imageList" @select="selectFileFun($event)" @delete="pickerDelete($event)"
:sizeType="sizeType" :imageStyles="imageStyles" :auto-upload="false" />
</view>
【3】script
export default {
data() {
return {
imageList: [],
sizeType: ['compressed'], //设置图片压缩
imageStyles: {
width: 120,
height: 120,
},
}
},
methods:{
//选择图片
selectFileFun(e) {
e.tempFilePaths.map(item => {
this.imageList.push({
name: 'imageList',
uri: item
})
})
},
pickerDelete(e) {
this.imageList.map((item, i) => {
if (item.uri == e.tempFilePath) {
this.imageList.splice(i, 1)
}
})
},
}
}
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'],//设置图片压缩compressed,原始图片original
sourceType: ['album', 'camera'],
success: (res) => {
console.log(res.tempFilePaths,'图片的本地文件路径列表');
}
});
https://editor.csdn.net/md/?articleId=126724165
/**
* H5端图片压缩
* 参数说明:
* imgSrc 图片url
* scale缩放比例 0-1
* 返回base64
* callback 回调设置返回值
*/
translate(imgSrc, scale, callback) {
var img = new Image();
img.src = imgSrc;
img.onload = function() {
var that = this;
var h = that.height; // 默认按比例压缩
var w = that.width;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width = document.createAttribute("width");
width.nodeValue = w;
var height = document.createAttribute("height");
height.nodeValue = h;
canvas.setAttributeNode(width);
canvas.setAttributeNode(height);
ctx.drawImage(that, 0, 0, w, h);
var base64 = canvas.toDataURL('image/jpeg', scale); //压缩比例
canvas = null;
callback(base64);
}
},
//选择图片、视频
selectFileFun(e) {
const that = this
console.log('压缩前', e.tempFiles[0].size)
e.tempFilePaths.forEach(item => {
that.imageList.push({
name: 'imageList',
uri: imgUrl
})
})
},
//上传
uploadFile(){
const that = this
if (this.imageList.length > 0) {
this.imageList.forEach(item => {
that.translate(item.uri, 0.5, imgURL => {
//查看压缩后的大小
uni.getFileInfo({
filePath: imgUrl,
success: imgInfo => {
console.log('压缩后', imgInfo.size);
}
})
item.uri = imgURL
})
})
}
...
}
uni.uploadFile({
url: url,//上传图片的地址
filePath: ...,//这里是图片的本地文件路径列表(选择图片成功的时候可以拿到,在上边的success回调中res.tempFilePaths即可拿到)
name: '',//上传的名字叫啥都行
headers: {
accessToken: //可以设置你的请求头的token噢
},
success(res) {
//上传成功的回调
这个res是后端返回给你上传成功的数据里边一般会有上传之后图片的在线路径
}
})
或者
uni.uploadFile({
url: url,
files: flieList,//flieList图片等
formData: param,//其它上传参数
header: {
"token": uni.getStorageSync('Token')
},
success: (res) => {
console.log(res)
},
fail: error => {
uni.showModal({
title: '提示',
content: error,
showCancel: false
});
uni.hideLoading();
},
complete: () => {
uni.hideLoading();
}
});
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。