在三年前前也寫過關於阿里雲OSS上傳的,但是當時使用的Express。
Node.js阿里雲OSS文件上傳
這次使用的Egg.js,在實際操作中也發現阿里雲OSS的文檔和官網操作有了一些變化了。
在下面的操作需要有先看看如下文檔:
Egg.js-獲取上傳的文件
對象存儲 OSS > SDK 參考 > Node.js
對象存儲 OSS > 開發指南 > 訪問域名(Endpoint) > 訪問域名和數據中心
egg-multipart
在 config/config.default.js
文件中啓用 file 模式:
const config = exports = {
// 文件上傳
// https://eggjs.org/zh-cn/basics/controller.html#獲取上傳的文件
multipart: {
mode: 'file',
fileSize: '50mb', // 接收文件大小
whitelist: [ // 允許接收的文件類型
'.png',
'.jpg'
],
}
}
config/config.default.js
中解決跨域問題
config.cors = {
origin:'*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
};
編寫前端測試代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="POST" action="http://localhost:7001/alioss/upload" enctype="multipart/form-data">
file: <input name="file" type="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
後端代碼
'use strict';
// https://help.aliyun.com/document_detail/32068.html
const Controller = require('egg').Controller;
const fs = require('mz/fs');
let OSS = require('ali-oss');
let aliInfo = {
// https://help.aliyun.com/document_detail/31837.html
region: 'oss-cn-shenzhen',
bucket: 'qxxxxxxxxx',
accessKeyId: 'LxxxxxxxxxxxxB',
accessKeySecret: 'Ixxxxxxxxxxxxxxxxi'
}
let client = new OSS(aliInfo);
class AliOssController extends Controller {
async upload() {
const { ctx } = this;
const file = ctx.request.files[0];
let result;
try {
// https://help.aliyun.com/document_detail/111265.html
// 處理文件,比如上傳到雲端
result = await client.put(file.filename, file.filepath);
} finally {
// 需要刪除臨時文件
await fs.unlink(file.filepath);
}
ctx.body = {
url: result.url,
// 獲取所有的字段值
requestBody: result,
};
}
}
module.exports = AliOssController;
註冊路由
router.post('/alioss/upload', controller.alioss.upload);
到這裏整個過程就完畢了。
微信小程序也可使用
上面的後端上傳接口在微信小程序中也是可以正常使用的,親測有效。
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success (res1) {
const tempFilePaths = res1.tempFilePaths[0]
// tempFilePath可以作爲img標籤的src屬性顯示圖片
wx.uploadFile({
url: 'http://localhost:7001/alioss/upload',
filePath: tempFilePaths,
name: 'file',
success (res) {
},
fail (res) {
}
})
}
})