iview:
html部分
<Upload :action="fileAction" :show-upload-list="false" accept="image/*" :on-format-error="handleFormatError" :before-upload="getOssSignData" :on-success="uplloadSucess" ref="uploadfile" multiple>
<div @click="updata">
<Icon type="ios-camera" size="25" style="border:1px solid #57a3f3;height:40px;width:40px;text-align:center;padding-top:7px;"></Icon>
</div>
</Upload>
<div style="overflow-x:auto;max-width:630px;display:flex;">
<div v-for="(item,index) in beforeimg" :key="index" style="display:flex;margin-left:16px;">
<div v-viewer>
<img :src="item" style="width:60px;height:60px;border-radius: 0.5vw;" /></div>
<div @click="deletePic(item)">
<img style="width:15px;height:15px;cursor: pointer;margin-top:4px;margin-left:-15px" :src="deleIconurl"/>
</div>
</div>
/div>
methods部分
//文件上传成功
uplloadSucess(response, file, fileLists) {
debugger
if (this.urlimg == "") {
this.urlimg = response.data.linkUrl;
} else { this.urlimg = this.urlimg + "," + response.data.linkUrl; }
this.$Message.success({ content: "上传成功", duration: 3 });
var url = '存放图片的url地址' + response.data.linkUrl.split("IMG\\")[1];
//this.beforeimg = [];
this.beforeimg.push(url);
//console.log(this.beforeimg);
},
/* 上传失败 */
uplloadError(error, file, fileLists) {
this.$Message.error({ content: "上传失败", duration: 3 });
},
updata() {
//上传
this.$refs.uploadfile.clearFiles(); //清除路径
this.fileAction = 接口地址
},
handleFormatError() {
this.$Message.error("上传图片格式错误,请上传'jpg','jpeg','png'格式");
},
getOssSignData(file) {
return new Promise((resolve, reject) => {
let isLt1M = file.size / 1024 / 1024 < 1;
if (isLt1M) {
console.log("图片不超过1M不压缩") // 这里是调取后台请求阿里oss签名的接口
resolve(file); // 返回图片file对象,这里图片不超过1M就不用压缩直接返回file
} else {
// let that = this; // new Compressor里面的success方法会修改this指向本来是想用that替代的但是,请求后台oss接口that指向的$store方法里没有所以采用箭头函数的形势去除success方法this指向内部函数
console.log("图片压缩前", file.size)
new Compressor(file, { width: 1080, // 压缩完成的宽度,高度会自适应
quality: 0.6, // 压缩的质量,不加上面的宽度话压缩效果很不理想,体积基本没有变化,一定要加个宽或者高度
success: res =>{ // 箭头函数的形势去除success this指向内部函数的
res = new File([res], res.name, { // 返回的结果是个blob对象,阿里oss上传要file对象这里使用js内置函数将其3转为file对象
type: res.type,
lastModified: Date.now()
});
console.log("图片压缩", res)
resolve(res); // 重点 返回压缩的图片对象
},
error(err) {
reject(err)
}
});
}
});
}, //删除图片
deletePic(picurl) {
let imgsArr = this.beforeimg;
let imgs = [];
let needimgs = [];
for (var i = 0; i < imgsArr.length; i++) {
imgs.push(imgsArr[i]);
}
let index = imgs.indexOf(picurl);
if (index !== -1) {
imgs.splice(index, 1); //删除点击删除按钮的数据项
}
for (let i = 0; i < imgs.length; i++) {
needimgs.push(imgs[i]);
}
this.beforeimg = needimgs;
let delpicurl = picurl.split("pkylfile/img/")[1];
let oldurlimg = this.urlimg.split(",");
this.urlimg = [];
for (let l = 0; l < oldurlimg.length; l++) {
if (delpicurl == oldurlimg[l]) {
continue;
}
if (this.urlimg == "") {
this.urlimg = oldurlimg[l];
} else {
this.urlimg = this.urlimg + "," + oldurlimg[l];
}
}
},
Vant:
html部分
<van-cascader
v-model="cascaderValue"
title="内容"
:options="prolist"
@close="showtPicker = false"
active-color='#1989fa'
@finish="onFinish"
/>
methods部分
onRead(e) {
let _this = this
if (e && e.length) { // 判断是否是多图上传 多图则循环添加进去
e.forEach(item => {
let type = item.file.type // 获取类型
let name = common.generateUUID() + '.jpg' // 获取文件名
item.file.names = name
_this.imgPreview(item.file, name, type)
})
} else {
let type = e.file.type // 获取类型
let name = common.generateUUID() + '.jpg' // 获取文件名
e.file.names = name
_this.imgPreview(e.file, name, type)
};
let formdata = new FormData();
formdata.append('file', e.file)
axios.post(接口地址,formdata,{
headers:{'Content-Type': 'application/json'}
})
.then(res=>{
console.log(res);
var url = '存放图片的url地址' + res.data.data.linkUrl.split("IMG\\")[1];
//console.log(url);
this.imgUrl.push(url);
})
.catch(err=>{
console.log(err);
})
},
// 处理图片
imgPreview(file, name, type) {
let self = this
let Orientation
let filename = name
// 看支持不支持FileReader
if (!file || !window.FileReader) return
if (/^image/.test(file.type)) {
// 创建一个reader
let reader = new FileReader()
// 将图片2将转成 base64 格式
reader.readAsDataURL(file)
// 读取成功后的回调
reader.onloadend = function() {
let result = this.result
let img = new Image()
img.src = result
// 判断图片是否大于500K,是就直接上传,反之压缩图片
if (this.result.length <= 500 * 1024) {
let file = common.dataURLtoFile(this.result, filename, type)
self.postImg(file)
} else {
img.onload = function() {
let data = common.compress(img, Orientation)
let file = common.dataURLtoFile(data, filename, type)
self.postImg(file)
}
}
}
}
},
postImg(file) {
this.imglist.push(file)
},
uniapp
html部分
<view class="cu-bar bg-white" style="border-top:1upx solid #ddd;">
<view class="action">上传照片</view>
<view class="action">{{imgList.length}}/10</view>
</view>
<view class="cu-form-group">
<view class="grid col-4 grid-square flex-sub">
<view v-if="imgList.length>0" class="bg-img" v-for="(item,index) in imgList" :key="index"
@tap="ViewImage" :data-url="imgList[index]">
<image :src="imgList[index]" mode="aspectFill"></image>
<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
<text class='cuIcon-close'></text>
</view>
</view>
<view class="solids" @tap="addImage" v-if="imgList.length<1">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
</view>
methods部分
//选择图片
addImage() {
var that = this;
// 从本地相册选择图片或使用相机拍照。
uni.chooseImage({
count: 10, //最多可以选择的图片张数,默认9
//album 从相册选图,camera 使用相机,默认二者都有。
sourceType: ['album', 'camera'],
success: function(res) {
//imgList为data中定义的一个数组 保存选择的图片数组(res.tempFilePaths)
that.imgList = res.tempFilePaths
that.upload(res)
}
})
},
upload(imgList) {
const that = this
let imgs = [];
imgList.tempFiles.forEach(v => {
imgs.push({
name: 'file',
uri: v.path
})
})
let data = {};
let baseUrl = '接口地址'
uni.uploadFile({
url: baseUrl,
files: imgs,
formData: data,
success: (res) => {
console.log(JSON.parse(res.data))
uni.showToast({
title: '上传成功',
icon: 'success',
duration: 1000,
})
var res = JSON.parse(res.data)
var url = '存放图片的url地址' + res.data.linkUrl.split("IMG\\")[1];
this.afterImgUrl.push(url);
console.log(this.afterImgUrl);
},
fail: (err) => {
console.log(err)
// uni.showModal({
// content: err.errMsg,
// showCancel: false
// })
// this.issubmit = false;
},
});