上一篇我写了oss上传的基本使用,是用的弹框的,当时是想在不改变原有代码前提下弹个框,不会影响原有的业务逻辑,减少可能出bug的可能性,但是我写完组件后发现有一些上传图片本身就在弹框里,在弹个框用户体验非常不好,又不想每个页面都写一遍,所以我决定写个公共方法,这里我是写在common.js里了,
// 图片上传 var OSS = require(‘ali-oss‘) var ossClient var partSize = 1024 * 1024 * 10 var parallel = 5 // 同时上传的分片数 var backObj = {} const imageUpload = function (file, callback) { $api.user.getStsToken({}).then(({ data }) => { if (data && data.head.retCode === ‘0000‘) { var credentials = data.body const { accessKeyId, accessKeySecret, securityToken, bucketName } = credentials ossClient = new OSS({ accessKeyId: accessKeyId, accessKeySecret: accessKeySecret, stsToken: securityToken, bucket: bucketName, // utility secure: true, region: ‘oss-cn-beijing‘, // todo folder: ‘customer‘ }) if (ossClient) { var { raw } = file var fileList = [raw] fileList.forEach(file => { if (file.size < partSize) { commonUpload(file, callback) } else { multipartUpload(file, callback) } }) } else { this.statusMsg = ‘initOSSClient异常空,请刷新重试或联系管理员‘ } } else { this.statusMsg = ‘sts临时凭证获取失败,请刷新重试或联系管理员‘ } }) } function commonUpload (file, callback) { var newFileName = new Date().getTime() + Math.random().toString(36).substr(2) + file.name.substr(file.name.indexOf(‘.‘)) ossClient.put(‘customer‘ + ‘/‘ + newFileName, file).then(result => { backObj = result backObj.size = file.size backObj.oldName = file.name callback(backObj) }).catch(err => { console.log(`Common upload ${file.name} failed === `, err) }) } // 分片上传 function multipartUpload (file, callback) { var newFileName = new Date().getTime() + Math.random().toString(36).substr(2) + file.name.substr(file.name.indexOf(‘.‘)) return ossClient.multipartUpload(‘customer‘ + ‘/‘ + newFileName, file, { parallel, partSize, progress: this.onMultipartUploadProgress }).then(result => { backObj = result backObj.size = file.size backObj.oldName = file.name callback(backObj) }).catch(err => { console.log(`Multipart upload ${file.name} failed === `, err) }) }
export {
imageUpload
}
这里我也是费了点时间的,由于菜鸟本菜一根筋,想着写一个方法然后return 出去,异想天开的以为能拿到参数,但是参数是在方法回调的里,不能直接return,用异步不不行,血的教训啊,浪费了好几个小时,最后用的回调,划重点哈
这里是调用的方法
先是引用
html是这样写的
import { imageUpload } from ‘@utils/common‘
好啦今天就写道这,有问题欢迎指教,多多评论,一起探讨