1.创建bucket
2.创建AccessKey
3.设置跨域
4.安装ali-oss
- 安装ali-oss
npm i --save ali-oss
5.配置一个OSS模块
const OSS = require('ali-oss');
const client = new OSS({
bucket: 'xxxxxx',
region: 'oss-cn-beijing',
accessKeyId: 'xxxxxx',
accessKeySecret: 'xxxxxx'
});
export default client;
6.vue组件里使用
- 引入client
import client from '../../config/aliOss.ts';
- 获取文件对象(本文使用的是element-ui的el-upload组件),注意该组件封装后原始文件对象保存在raw属性里,类型是File。
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
list-type="picture-card"
:auto-upload="false"
:limit="4"
:file-list="fileList"
:http-request="Upload"
:on-change="handleChange"
:on-remove="handleRemove">
<i class="el-icon-plus"></i>
</el-upload>
组件相关属性请参考element-ui。
- 代码实现上传图片
async Upload() {
try {
//object-name可以自定义为文件名(例如file.txt)或目录(例如abc/test/file.txt)的形式,
// 实现将文件上传至当前Bucket或Bucket下的指定目录。
for(var i = 0; i < this.fileList.length; i++) {
let file = this.fileList[i];
let name = file.name.substring(0, file.name.indexOf('.'));
let result = await client.multipartUpload(name, file.raw); // 注意原始文件对象保存在raw里
console.log(result);
}
} catch (e) {
console.log(e);
}
}
7.上传成功后
- 上述便是上传图片到阿里云的使用步骤,作为一个初次使用OSS的菜鸟,希望这篇文章能帮助到小伙伴们。