aliyun-oss-sdk 引入###
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
1
注意:这里看网上有朋友说不能用npm install ali-oss --save的方式用于前端页面的使用,这里自己没有进行测试,感兴趣的朋友可以试试,有结果了希望在下方评论来告知,感谢
上传方法的封装
这里OSS上传的方法封装到了oss.js文件中
直接上代码
import co from 'co'
const OSSConfig = {
uploadHost: 'http://jinanluke.oss-cn-beijing.aliyuncs.com', //OSS上传地址
type: 'scs',
ossParams: {
region: 'oss-cn-beijing',
success_action_status: '200', // 默认200
accessKeyId: '私人accessKeyId',
accessKeySecret: 'accessKeySecret',
bucket: '私人bucket',
},
}
function random_string(len) {
len = len || 32
var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
var maxPos = chars.length
var pwd = ''
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos))
}
return pwd
}
/**
*
* @param event 上传图片的资源路径
* @param type 图片资源类型
* @param dir oss要保存的文件夹
* @returns {OSS文件路径}
*/
function uploadOSS(event, type,dir = 'file/') {
return new Promise((resolve, reject) => {
var client = new OSS({
region: OSSConfig.ossParams.region,
accessKeyId: OSSConfig.ossParams.accessKeyId,
accessKeySecret: OSSConfig.ossParams.accessKeySecret,
bucket: OSSConfig.ossParams.bucket,
});
var file;
if (type == 0) {
file = event;
} else {
file = event.target.files[0];
}
let randomName = `${dir}${random_string(6)}_${file.name}`;
co(function* () {
var result = yield client.multipartUpload(randomName, file);
console.log(`${OSSConfig.uploadHost}/${result.name}`);
resolve(`${OSSConfig.uploadHost}/${result.name}`);
}).catch(function (err) {
console.log(err);
reject(err);
});
});
}
export { uploadOSS }
OSS平台配置###
在平台的概览里面看看自己的基础设置里面的读写权限是否改为了公共读,我这边只有配置公共读才上传并且回显图片成功,其他情况还请朋友告知,谢谢
关于跨域访问的配置
页面内调用###
页面代码这里大概写一下
<div class="wrapper">
<span class="text">头像</span>
<div class="img" @click.stop="uploadHeadImg">
<img :src="userData.img" width="40" height="40" alt="">
<i class="icon"></i>
</div>
<input type="file" id="file" accept="image/*" @change="handleFile" class="hiddenInput" />
</div>
import { uploadOSS } from '@t/oss'
methods: {
async handleFile(event) {
this.imgUrl = await uploadOSS(event)
},
}
原文链接:[https://blog.csdn.net/AsdfgJiao/article/details/92800701]