uniapp(uview)上传图片
单张:
let _this = this
uni.chooseImage({
count: 1, //默认9
sizeType: ['compressed'],
sourceType: ['album'],
success: res => {
let tiemr = new Date();
let address = tiemr.getFullYear() + '' + (tiemr.getMonth() + 1) + '' + tiemr.getDate();
address = 'happySingle/' + address + '/';
var imageSrc = res.tempFilePaths[0];
let str = res.tempFilePaths[0].substr(res.tempFilePaths[0].lastIndexOf('.'));
let nameStr = address + tiemr.getTime() + str;
let ossUrl = _this.aliOss.host + '/';
uni.uploadFile({
url: ossUrl, //输入你的bucketname.endpoint
filePath: imageSrc,
fileType: 'image',
name: 'file',
formData: {
name: nameStr,
key: nameStr,
policy: _this.aliOss.policy, // 输入你获取的的policy
OSSAccessKeyId: _this.aliOss.accessid, // 输入你的AccessKeyId
success_action_status: '200', // 让服务端返回200,不然,默认会返回204
signature: _this.aliOss.signature // 输入你获取的的signature
},
success: res => {
if (res.statusCode == '200') {
_this.formData.topImg = ossUrl + nameStr
} else {
uni.showToast({
title: '上传图片失败',
duration: 2000
});
}
}
});
}
});
多张:
let _this = this
_this.fileList5 = event.file
console.log(_this.fileList5, '_this.fileList5')
for (let i = 0; i < _this.fileList5.length; i++) {
let ossUrl = _this.aliOss.host + '/';
let tiemr = new Date();
let address = tiemr.getFullYear() + '' + (tiemr.getMonth() + 1) + '' + tiemr.getDate();
address = 'happySingle/' + address + '/';
var imageSrc = _this.fileList5[i].url
let str = _this.fileList5[i].url.substr(_this.fileList5[i].url.lastIndexOf('.'));
let nameStr = address + tiemr.getTime() + str;
console.log(imageSrc, 'imageSrc')
uni.uploadFile({
url: ossUrl, //输入你的bucketname.endpoint
filePath: imageSrc,
fileType: 'image',
name: 'file',
formData: {
name: nameStr,
key: nameStr,
policy: _this.aliOss.policy, // 输入你获取的的policy
OSSAccessKeyId: _this.aliOss.accessid, // 输入你的AccessKeyId
success_action_status: '200', // 让服务端返回200,不然,默认会返回204
signature: _this.aliOss.signature // 输入你获取的的signature
},
success: res => {
if (res.statusCode == '200') {
console.log(ossUrl + nameStr)
// _this.imgArr.push(ossUrl + nameStr) 异步
_this.imgArr[i] = ossUrl + nameStr 同步
_this.formData.showImg = _this.imgArr.join(',')
} else {
uni.showToast({
title: '上传图片失败',
duration: 2000
});
}
}
});
}