圖片上傳在實(shí)際場景中使用廣泛,例如商品圖片,汽車圖片等等
一,場景
實(shí)現(xiàn)選擇單張圖片上傳,可以刪除圖片。(預(yù)覽功能時間原因未研究)文章來源:http://www.zghlxwxcb.cn/news/detail-745590.html
二,實(shí)現(xiàn)
Vue2 版本,使用uni-app框架api喚起手機(jī)相冊等圖片源,將圖片選中到目標(biāo)列表,并發(fā)送到服務(wù)器存儲,存儲成功得到處理后的圖片名稱存儲到字段中。文章來源地址http://www.zghlxwxcb.cn/news/detail-745590.html
<template>
<view class="cu-form-group" style="border-top: 20rpx solid #eee;">
<view class="action">
圖片
</view>
<view class="action">
{{imgList.length}} / 4
</view>
</view>
<view class="cu-form-group" style="border-top: 0rpx solid #eee;">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" v-for="(item,index) in imgList" :key="index"
:data-url="imgList[index]">
<image :src=baseUrl+item 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="chooseImage" v-if="imgList.length < count">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
//圖片總允許上傳數(shù)目
count: 4,
//存儲服務(wù)器返回的文件名稱
imgList: [],
//存儲選擇的本地圖片文件路徑列表
tempImgList: [],
//服務(wù)器圖片資源獲取接口
baseUrl: 'http://xxxxx/systemConfig/static/',
},
methods: {
/**
* 上傳圖片到服務(wù)器
*/
uploadImg(){
uni.uploadFile({
url: 'http://xxxxx/systemConfig/upload', //真實(shí)的接口地址
//每次保存最新的圖片到服務(wù)器
filePath: this.tempImgList[this.tempImgList.length-1],
name: 'file',
header: {
'content-type': 'multipart/form-data',
'X-Access-Token': uni.getStorageSync('Access-Token')
},
success: (uploadFileRes) => {
let ress = JSON.parse(uploadFileRes.data)
//將服務(wù)器返回的文件名進(jìn)行存儲,存儲到記錄對象中,使能從服務(wù)器獲取圖片資源
this.imgList.push(ress.data);
}
});
},
/**
* 選擇圖片上傳
*/
chooseImage() {
uni.chooseImage({
count: 1, //單詞最多允許選中,默認(rèn)9
sizeType: ['original', 'compressed'], //可以指定是原圖還是壓縮圖,默認(rèn)二者都有
sourceType: ['album'], //從相冊選擇
success: (res) => {
// 獲取到圖片的本地文件路徑列表,存儲到臨時列表tempImgList中
if (this.tempImgList.length != 0) {
this.tempImgList = this.tempImgList.concat(res.tempFilePaths)
} else {
this.tempImgList = res.tempFilePaths
}
this.uploadImg()
}
});
},
/**
* 預(yù)覽圖片 urls所有的url地址,current選中的url地址
* @param {Object} e
*/
viewImage(e) {
uni.previewImage({
urls: this.imgList,
current: e.currentTarget.dataset.url
});
},
/**
* 刪除圖片
* @param {Object} e
*/
delImg(e) {
uni.showModal({
title: '',
content: '確定要刪除第'+(e.currentTarget.dataset.index+1)+'張圖片嗎?',
cancelText: '再看看',
confirmText: '確定',
success: res => {
if (res.confirm) {
this.imgList.splice(e.currentTarget.dataset.index, 1)
}
}
})
},
}
}
</script>
<style>
.cu-form-group .title {
min-width: calc(4em + 15px);
}
</style>
三,效果
- 無照片時
- 多張圖片時
- 滿圖片時
- 刪除第n張圖片
到了這里,關(guān)于【uni-app】上傳圖片 uni.chooseImage(),uni.uploadFile()接口使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!