# 基于nodejs的前端直傳oss
## 阿里云oss權(quán)限設(shè)置叶眉、跨域設(shè)置
### 權(quán)限設(shè)置
![UTOOLS1588380940382.png](https://johnnycc.oss-cn-beijing.aliyuncs.com/UTOOLS1588380940382.png)
![UTOOLS1588380971582.png](https://johnnycc.oss-cn-beijing.aliyuncs.com/UTOOLS1588380971582.png)
### 跨域設(shè)置
![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({
? ? ? ? ? //服務(wù)器地區(qū)
? ? ? ? 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
? ? ? ? ? )
? ? ? ? ? //獲得結(jié)果中返回的url
? ? ? ? ? _this.avatar = result.url
? ? ? ? ? _this.changeMessage()
? ? ? ? } catch (e) {
? ? ? ? ? console.log(e)
? ? ? ? }
? ? ? }
? ? ? put()
? ? }
```
更多內(nèi)容大家可以關(guān)注Johnny博客