写在前面:这个只是对小程序提供的API进行了简单的封装,并没有什么特别牛的技术,记录下小程序的开发过程而已
感谢参考,再次感谢!
小程序请求部分的信息
需求
1.设置最大图片数,选满后添加按钮消失;
2.支持选择后删除图片;
3.查看大图;
4.上传图片到指定服务器;
如何使用
1.把文件拖到项目里
2.使用upload-image
3.完成。。。。
关键代码:
// upload-image.js
import {
httpUtil,
LogUtil,
} from '../../../../utils/utils.js'
Component({
/**
* 组件的属性列表
*/
properties: {
maxCount: {
type: Number,
value: 6,
observer: function(newVal, oldVal) {
this.setData({
currentLastCount: newVal
});
}
}
},
/**
* 组件的初始数据
*/
data: {
currentLastCount: 0,
images: []
},
/**
* 组件的方法列表
*/
methods: {
addImage() {
wx.chooseImage({
sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
success: res => {
const tempFilePaths = this.data.images.concat(res.tempFilePaths)
var tempImages = []
for (var i = 0; i < tempFilePaths.length; i++) {
var image = {
path: tempFilePaths[i],
value: {
uploaded: false,
uploadStatus: "defaultStatus",
url: ''
}
}
tempImages.push(image)
console.log('tempImages' + tempImages)
}
this.setData({
images: tempImages.length <= this.data.maxCount ? tempImages : tempImages.slice(0, this.data.maxCount),
currentLastCount: this.data.maxCount - tempImages.length,
})
for (var i = 0; i < tempImages.length; i++) {
this.uploadpicture(tempImages[i])
}
}
})
},
/**
* 上传图片
*/
uploadpicture(image) {
console.log('上传之前的image', image)
var thatImages = this.images;
const success = function(data) {
console.log('上传成功的image', image)
if (data && data.length > 0) { ////自己替换
const model = data[0];
const url = model.key;
// for (var i = 0; i < thatImages.length; i++) {
// if (thatImages[i].path === image.path) {
image.value.uploaded = true;
image.value.uploadStatus = 'success';
if (url) {
image.value.url = url
}
// thatImages[i] = image
this.setData({
images: [image],
})
// }
// }
console.log('修改之后的image' + image)
}
}
const fail = function(e) {
console.log(e)
}
const progress = function(res) {
console.log('上传进度', res.progress + image.path + image.uploadStatus + image.uploaded)
}
httpUtil.uploadFile(image.path, success, fail, progress)
},
removeImage(e) {
const idx = e.target.dataset.idx;
this.data.images.splice(idx, 1);
this.setData({
images: this.data.images,
currentLastCount: this.data.maxCount - this.data.images.length
})
},
handleImagePreview(e) {
const idx = e.target.dataset.idx
const images = this.data.images
wx.previewImage({
current: images[idx], //当前预览的图片
urls: images, //所有要预览的图片
})
}
}
})