阿里oss上传工具函数

阿里oss上传工具函数,首先需要先安装依赖 npm install ali-oss,还有上传支持压缩使用到了 compressorjs 这个工具库;randomString这个是自写的生成随机字串的函数,用来保证文件名唯一。

  1 import OSS from 'ali-oss';
  2 import Compressor from 'compressorjs';
  3 import { randomString } from '@/utils/index.js';
  4 
  5 const { accessKeyId, accessKeySecret, region, endpoint } = {
  6   region: 'your region',
  7   accessKeyId: 'your accessKeyId',
  8   accessKeySecret: 'your accessKeySecret',
  9   endpoint: 'oss-cn-hangzhou.aliyuncs.com'
 10 };
 11 
 12 const client = new OSS({
 13   // yourRegion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou。
 14   region: region,
 15   // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
 16   accessKeyId: accessKeyId,
 17   accessKeySecret: accessKeySecret,
 18   endpoint: endpoint,
 19   // 填写Bucket名称。
 20   bucket: 'mdhw'
 21 });
 22 /**
 23  * 图片压缩
 24  */
 25 function compressImage(fileList, backType, limitSize, quality) {
 26   const promiseAry = [];
 27   const maxSize = limitSize * 1024 * 1024;
 28   fileList.forEach(image => {
 29     promiseAry.push(new Promise((resolve, reject) => {
 30       if (image.size <= maxSize) { // 没操过限制,不用压缩
 31         resolve(image)
 32       }
 33       else {
 34         new Compressor(image, {
 35           // maxWidth: 750,
 36           // maxHeight: 750,
 37           quality: quality || 0.8,
 38           success(result) {
 39             let file = new File([result], image.name, { type: image.type })
 40 
 41             if (!backType || backType == 'blob') {
 42               resolve(result)
 43             } else if (backType == 'file') {
 44               resolve(file)
 45             } else {
 46               resolve(file)
 47             }
 48           },
 49           error(err) {
 50             console.log('图片压缩失败---->>>>>', err)
 51             resolve(image)
 52           }
 53         })
 54       }
 55     }))
 56   })
 57   return Promise.all(promiseAry)
 58 }
 59 
 60 const defaultLimit = 1;
 61 /**
 62  *
 63  * @param fileList 上传图片的资源路径
 64  * @param dir oss要保存的文件夹
 65  * @param limitSize oss图片限制 默认1m 0为不限制
 66  * @returns {OSS文件路径}
 67  */
 68 
 69 async function uploadOSS(fileList, dir = 'file', {
 70   limitSize = defaultLimit, compress = false
 71 }) {
 72   return new Promise((resolve, reject) => {
 73     const promiseAry = [];
 74     let randomVal, randomStr, imgtype, fileName, tmpAry, maxSize = limitSize * 1024 * 1024;
 75     let _Promise = compress ? compressImage(fileList, 'file', limitSize) : Promise.resolve(fileList)
 76 
 77     if (compress) {
 78       console.log('压缩前的图片列表', fileList)
 79     }
 80     _Promise.then(fileList => {
 81       if (compress) {
 82         console.log('压缩后的图片列表', fileList)
 83       }
 84       const canUploadList = limitSize == 0 ? fileList : fileList.filter(file => file.size <= maxSize);
 85       canUploadList.forEach(file => {
 86 
 87         tmpAry = file.name.split('.');
 88         imgtype = tmpAry[tmpAry.length - 1]
 89         randomVal = +new Date();
 90         randomStr = randomString()
 91         fileName = `${randomVal}_${randomStr}.${imgtype}`
 92         promiseAry.push(client.put(`${dir}/${fileName}`, file, {
 93           headers: {
 94             'aa': 'aa'
 95           }
 96         }))
 97       })
 98       Promise.all(promiseAry).then(result => {
 99         let code = canUploadList.length == fileList.length ? 1 : 0
100         resolve({
101           result,
102           code,
103           msg: code == 1 ? '上传成功' : `${fileList.length == 1 ? '' : '部分'}图片大小超过${limitSize}M`
104         });
105       }).catch(e => {
106         reject(e)
107       })
108     })
109 
110   });
111 }
112 
113 export { uploadOSS, defaultLimit }

 

posted @ 2022-05-13 14:26  豆浆不要油条  阅读(192)  评论(0编辑  收藏  举报