цель обучения:
提示:uni-app上传主图及附图,单张图片与多张图片使用方法
Содержание обучения:
`Советы: uni-app загружает основное изображение и сопутствующие рисунки, как использовать одно изображение и несколько изображений
Например:
- Загрузить с использованием компонентов
- получить значение
- метод называется
- установить значение свойства
- Получить список рисунков
Подведем итог:
Подведем итог:
- 1. Загруженные компоненты
//选择主图
ChooseMainImage() {
uni.chooseImage({
count: 10, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
var imagePathArr =res.tempFilePaths
uni.showToast({
title: '上传进度:0/' + imagePathArr.length,
icon: 'none',
mask: false
});
var remoteIndexStart = this.imageList.length - imagePathArr.length
var promiseWorkList = []
var keyname = (this.fileKeyName ? this.fileKeyName : 'file')
var completeImages = 0
for (let i = 0; i < imagePathArr.length; i++) {
promiseWorkList.push(new Promise((resolve, reject) => {
let header = {"Mema-Token":this.$api.config.header["Mema-Token"]};
let remoteUrlIndex = remoteIndexStart + i;
uni.uploadFile({
url: this.imageServerUrl,
// methods: 'POST',
// fileType: 'image',
header: header,
formData: this.uploadDataMain,
filePath: imagePathArr[i],
name: keyname,
success: function(res) {
if (res.statusCode === 200) {
var jsonData = JSON.parse(res.data);
if(jsonData.code == 0){
completeImages++
uni.showToast({
title: '上传进度:' + completeImages + '/' + imagePathArr.length,
icon: 'none',
mask: false,
duration: 500
});
resolve(jsonData.data)
}else{
uni.showToast({
icon: 'none',
position: 'bottom',
title: jsonData.msg
});
}
} else {
reject('fail to upload image:' + remoteUrlIndex)
}
},
fail: function(res) {
reject('fail to upload image:' + remoteUrlIndex)
}
})
}))
}
Promise.all(promiseWorkList).then((result) => {
for (let i = 0; i < result.length; i++) {
// result[i].url = this.$api.config.baseUrl + result[i].url
this.imageList.push(result[i])
}
})
}
});
},
//查看主图
ViewMainImage(e) {
var images = [];
for (let i = 0; i < this.imageList.length; i++) {
images.push(this.$api.config.baseUrl + this.imageList[i].url)
}
uni.previewImage({
urls: images,
current: e.currentTarget.dataset.url
});
},
//删除主图
DelMainImg(e) {
var imgObj = this.imageList[e.currentTarget.dataset.index]
uni.showModal({
title: '删除图片',
content: '确定要删除吗?',
cancelText: '再看看',
confirmText: '确认删除',
success: res => {
if (res.confirm) {
this.pic=""
this.imageList = []
}
}
})
},
//上传附图
ChooseFigureImage() {
uni.chooseImage({
count: 10, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
var imagePathArr = res.tempFilePaths
uni.showToast({
title: '上传进度:0/' + imagePathArr.length,
icon: 'none',
mask: false
});
var remoteIndexStart = this.picList.length - imagePathArr.length
var promiseWorkList = []
var keyname = (this.fileKeyName ? this.fileKeyName : 'file')
var completeImages = 0
for (let i = 0; i < imagePathArr.length; i++) {
promiseWorkList.push(new Promise((resolve, reject) => {
let header = {"Mema-Token":this.$api.config.header["Mema-Token"]};
let remoteUrlIndex = remoteIndexStart + i;
uni.uploadFile({
url: this.imageServerUrl,
// methods: 'POST',
// fileType: 'image',
header: header,
formData: this.imageformData,
filePath: imagePathArr[i],
name: keyname,
success: function(res) {
if (res.statusCode === 200) {
var jsonData = JSON.parse(res.data);
if(jsonData.code == 0){
completeImages++
uni.showToast({
title: '上传进度:' + completeImages + '/' + imagePathArr.length,
icon: 'none',
mask: false,
duration: 500
});
resolve(jsonData.data)
}else{
uni.showToast({
icon: 'none',
position: 'bottom',
title: jsonData.msg
});
}
} else {
reject('fail to upload image:' + remoteUrlIndex)
}
},
fail: function(res) {
reject('fail to upload image:' + remoteUrlIndex)
}
})
}))
}
Promise.all(promiseWorkList).then((result) => {
for (let i = 0; i < result.length; i++) {
// result[i].url = this.$api.config.baseUrl + result[i].url
this.picList.push(result[i])
}
})
}
});
},
//查看附图
ViewImage(e) {
var images = [];
for (let i = 0; i < this.picList.length; i++) {
// images.push(this.picList[i].url)
images.push(this.$api.config.baseUrl + this.picList[i].url)
}
uni.previewImage({
urls: images,
current: e.currentTarget.dataset.url
});
},
//删除附图
DelImg(e) {
var imgObj = this.picList[e.currentTarget.dataset.index]
uni.showModal({
title: '删除图片',
content: '确定要删除吗?',
cancelText: '再看看',
confirmText: '确认删除',
success: res => {
if (res.confirm) {
var data = []
var id = ''
if (imgObj) {
id = imgObj.id
if (id) {
data = [id]
}
}
this.$api.post("sys/oss/delete", { 'ids': data }).then((res)=>{
if(res.code == 0){
// 回调
this.picList.splice(e.currentTarget.dataset.index, 1)
}else{
uni.showToast({
icon: 'none',
position: 'bottom',
title: res.msg
});
}
})
}
}
})
},
- 2. Получите значение
var pic = "";
console.log(this.imageList) // 输出list
if(this.imageList.length > 0){
pic = this.imageList[0].url;
}
params.pic = pic;`
- 3. Способ вызова
//选择主图
ChooseMainImage() {
uni.chooseImage({
count: 10, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
var imagePathArr =res.tempFilePaths
uni.showToast({
title: '上传进度:0/' + imagePathArr.length,
icon: 'none',
mask: false
});
var remoteIndexStart = this.imageList.length - imagePathArr.length
var promiseWorkList = []
var keyname = (this.fileKeyName ? this.fileKeyName : 'file')
var completeImages = 0
for (let i = 0; i < imagePathArr.length; i++) {
promiseWorkList.push(new Promise((resolve, reject) => {
let header = {"Mema-Token":this.$api.config.header["Mema-Token"]};
let remoteUrlIndex = remoteIndexStart + i;
uni.uploadFile({
url: this.imageServerUrl,
// methods: 'POST',
// fileType: 'image',
header: header,
formData: this.uploadDataMain,
filePath: imagePathArr[i],
name: keyname,
success: function(res) {
if (res.statusCode === 200) {
var jsonData = JSON.parse(res.data);
if(jsonData.code == 0){
completeImages++
uni.showToast({
title: '上传进度:' + completeImages + '/' + imagePathArr.length,
icon: 'none',
mask: false,
duration: 500
});
resolve(jsonData.data)
}else{
uni.showToast({
icon: 'none',
position: 'bottom',
title: jsonData.msg
});
}
} else {
reject('fail to upload image:' + remoteUrlIndex)
}
},
fail: function(res) {
reject('fail to upload image:' + remoteUrlIndex)
}
})
}))
}
Promise.all(promiseWorkList).then((result) => {
for (let i = 0; i < result.length; i++) {
// result[i].url = this.$api.config.baseUrl + result[i].url
this.imageList.push(result[i])
}
})
}
});
},
//查看主图
ViewMainImage(e) {
var images = [];
for (let i = 0; i < this.imageList.length; i++) {
images.push(this.$api.config.baseUrl + this.imageList[i].url)
}
uni.previewImage({
urls: images,
current: e.currentTarget.dataset.url
});
},
//删除主图
DelMainImg(e) {
var imgObj = this.imageList[e.currentTarget.dataset.index]
uni.showModal({
title: '删除图片',
content: '确定要删除吗?',
cancelText: '再看看',
confirmText: '确认删除',
success: res => {
if (res.confirm) {
this.pic=""
this.imageList = []
}
}
})
},
//上传附图
ChooseFigureImage() {
uni.chooseImage({
count: 10, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
var imagePathArr = res.tempFilePaths
uni.showToast({
title: '上传进度:0/' + imagePathArr.length,
icon: 'none',
mask: false
});
var remoteIndexStart = this.picList.length - imagePathArr.length
var promiseWorkList = []
var keyname = (this.fileKeyName ? this.fileKeyName : 'file')
var completeImages = 0
for (let i = 0; i < imagePathArr.length; i++) {
promiseWorkList.push(new Promise((resolve, reject) => {
let header = {"Mema-Token":this.$api.config.header["Mema-Token"]};
let remoteUrlIndex = remoteIndexStart + i;
uni.uploadFile({
url: this.imageServerUrl,
// methods: 'POST',
// fileType: 'image',
header: header,
formData: this.imageformData,
filePath: imagePathArr[i],
name: keyname,
success: function(res) {
if (res.statusCode === 200) {
var jsonData = JSON.parse(res.data);
if(jsonData.code == 0){
completeImages++
uni.showToast({
title: '上传进度:' + completeImages + '/' + imagePathArr.length,
icon: 'none',
mask: false,
duration: 500
});
resolve(jsonData.data)
}else{
uni.showToast({
icon: 'none',
position: 'bottom',
title: jsonData.msg
});
}
} else {
reject('fail to upload image:' + remoteUrlIndex)
}
},
fail: function(res) {
reject('fail to upload image:' + remoteUrlIndex)
}
})
}))
}
Promise.all(promiseWorkList).then((result) => {
for (let i = 0; i < result.length; i++) {
// result[i].url = this.$api.config.baseUrl + result[i].url
this.picList.push(result[i])
}
})
}
});
},
//查看附图
ViewImage(e) {
var images = [];
for (let i = 0; i < this.picList.length; i++) {
// images.push(this.picList[i].url)
images.push(this.$api.config.baseUrl + this.picList[i].url)
}
uni.previewImage({
urls: images,
current: e.currentTarget.dataset.url
});
},
//删除附图
DelImg(e) {
var imgObj = this.picList[e.currentTarget.dataset.index]
uni.showModal({
title: '删除图片',
content: '确定要删除吗?',
cancelText: '再看看',
confirmText: '确认删除',
success: res => {
if (res.confirm) {
var data = []
var id = ''
if (imgObj) {
id = imgObj.id
if (id) {
data = [id]
}
}
this.$api.post("sys/oss/delete", { 'ids': data }).then((res)=>{
if(res.code == 0){
// 回调
this.picList.splice(e.currentTarget.dataset.index, 1)
}else{
uni.showToast({
icon: 'none',
position: 'bottom',
title: res.msg
});
}
})
}
}
})
},
- 4. Установите значение атрибута
pic: '',
baseUrl: this.$api.config.baseUrl,
imageServerUrl: this.$api.config.baseUrl + 'sys/oss/upload',//图片上传地址
uploadHeaders : {"Mema-Token":this.$api.config.header["Mema-Token"]},
fileKeyName : 'file',
uploadDataMain:{
relationTable:'device',
id:0,
isTable:0,
},
imageformData: {
relationTable:"device",
id:0,
isTable:1,
// type: 0
}, //图片上传时传递的参数
picList: [], //列表数据
imageList: [], //主图
- 5. Получите список чертежей
//获取附图
getPicList (deviceId) {
var that = this;
var param = {
pageForm: {
order: 'desc',
orderField: 'createDate',
page: 1,
limit: 50
},
dataForm: {
data: {
type: 0,//本地上传
relationTable:'device',
relationId:deviceId
},
op: {}
}
}
that.$api.post('/sys/oss/list',param).then(res => {
var picDataList = res.data.list ? res.data.list : []
that.picList = picDataList
}).catch(() => {})
return;
}