常规的Promise上传


<template><div><label for="upload" class="choose-img" :class="{'uploading-grey': isUploading}">选择图片上传</label><!-- input 的 multiple 属性,保证了input支持多选--><!-- accept="image/*" 可以用来限制选中的文件类型为图片类型--><input type="file" multiple id="upload"accept="image/*"@change="onChange":disabled="isUploading"ref="file"style="display: none"><p class="tip">提示: 一次可选择多张图片,最多不超过9张(单张图片大小 < 1M)</p></div></template><script>// 阿里云存储配套的依赖import OSS from 'ali-oss'export default{data() {return {// 传入阿里云存储的信息,生成连接用的信息对象clinet: new OSS({region: 'oss-cn-beijing',bucket: 'imooc-es',accessKeyId: '',accessKeySecret: ''}),// 专门存储,图片上传成功后的url地址imgList: [],// 判断图片是否处于上传中isUploading: false}},methods: {// 选取文件以及校验的过程onChange() {const newFiles = this.$refs?.file?.files// 校验选择图片的个数if (newFiles.length > 9) {alert('最多可选9张图片')return false}const files = []// 校验图片大小for (const file of newFiles) {// 将文件大小的单位转化成Mconst size = file.size / 1024 / 1024if (size > 1) {alert('请选择1M以内的图片')return false}files.push(file)}this.uploadFilesByOss(files)},// 处理文件上传到阿里云存储的过程uploadFilesByOss(files) {// 上传图片按钮置灰this.isUploading = trueconst uploadRequesst = []for(const file of files){uploadRequesst.push(new Promise((resolve, reject) =>{this.clinet.put(`${Math.random()}-${file.name}`, file).then(res => {resolve(res.url)}).catch(err => {console.log(err)reject(err)});}))}// 使用 Promise.allSettled 比 Promise.all 的好处就是// 即使有一个图片上传请求失败,不会影响其他图片上传请求的执行Promise.allSettled(uploadRequesst).then(res => {const imgs = []for (const item of res) {if(item.status === 'fulfilled'){imgs.push(item.value)}}this.imgList = imgs// 上传图片按钮恢复this.isUploading = false});}}}</script><style scoped>.choose-img{display: block;width: 150px;height: 50px;line-height: 50px;text-align: center;background-color: #42b983;color: #fff;border-radius: 5px;cursor: pointer;}/*表示上传图片按钮置灰*/.uploading-grey{background-color: #ccc;}.tip{color: #ccc;}</style>
Promise.allSettled() 上传图片后的返回值
更加优雅的异步操作
主要是针对 uploadFilesByOss() 方法的优化,使用 async/ await 对,阿里云存储中,图片上传过程的代码优化
去除了原来 Promise 中的回调操作
async uploadFilesByOss2(files) {
// 上传图片按钮置灰
this.isUploading = true
const imgs = []
for (const file of files) {
const res = await this.clinet.put(`${Math.random()}-${file.name}`, file)
imgs.push(res.url)
}
this.imgList = imgs
this.isUploading = false
}
