# 基于nodejs的前端直传oss
## 阿里云oss权限设置、跨域设置
### 权限设置
![UTOOLS1588380940382.png](https://johnnycc.oss-cn-beijing.aliyuncs.com/UTOOLS1588380940382.png)
![UTOOLS1588380971582.png](https://johnnycc.oss-cn-beijing.aliyuncs.com/UTOOLS1588380971582.png)
### 跨域设置
![UTOOLS1588381069493.png](https://johnnycc.oss-cn-beijing.aliyuncs.com/UTOOLS1588381069493.png)
## 安装ali-oss
npm install ali-oss
## 获取client对象
```javascript
getClient() {
let OSS = require('ali-oss')
this.client = new OSS({
//服务器地区
region: 'oss-cn-beijing',
//Accesstoken中的keyid
accessKeyId: 'LTAI4FhbwaMVJFsRBDFqqaB6',
//Accesstoken中的KeySecret
accessKeySecret: 'haBJpDQYdrUjqkZkUnXNEZT20fvdz9',
//bucket实例名称
bucket: 'johnnycc',
})
}
```
## 文件上传
```javascript
handleFile() {
//获取oss对象、client实例
this.getClient()
//取得用户选择的文件
this.file = this.$refs.upload.files[0]
var _this = this
async function put() {
try {
let result = await _this.client.put(
//传入文件名
_this.$refs.upload.files[0].name,
//传入文件
_this.file
)
//获得结果中返回的url
_this.avatar = result.url
_this.changeMessage()
} catch (e) {
console.log(e)
}
}
put()
}
```
更多内容大家可以关注Johnny博客