简介
源码地址:https://github.com/thinkasany/nestjs-course-code/tree/master/sdk/qiniu
配置bucket,然后去域名商后台解析cname,一直未配置成功可以查看官方文档,我重新注册了个二级域名就通过了。
通过dotenv解析env文件中的账号配置信息,path.resolve(__dirname, '../.env');
解决文件路径问题。
我的全栈项目nest中其实也有这部分的接口,但是毕竟项目文件太多了,express搭建一个更简易的,方便平常做一些功能。对nest感兴趣的可以看下面里面的写法,express足够的可以看上面的源码地址。
https://github.com/thinkasany/shop-server-nest
实现效果
代码
env
QINIU_ACCESS_KEY = ""
QINIU_SECRET_KEY = ""
QINIU_BUCKET = ""
service
// qiniuService.js
const qiniu = require('qiniu');
const path = require('path');
const dotenv = require('dotenv');
const envPath = path.resolve(__dirname, '../.env');
dotenv.config({ path: envPath });
const accessKey = process.env.QINIU_ACCESS_KEY;
const secretKey = process.env.QINIU_SECRET_KEY;
const bucket = process.env.QINIU_BUCKET;
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const config = new qiniu.conf.Config();
const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();
async function uploadToQiniu(fileBuffer) {
return new Promise((resolve, reject) => {
const options = {
scope: bucket,
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
formUploader.put(uploadToken, null, fileBuffer, putExtra, (respErr, respBody, respInfo) => {
if (respErr) {
reject(respErr);
} else if (respInfo.statusCode === 200) {
const imageUrl = `http://qniu.xxlb.site//${respBody.key}`;
resolve(imageUrl);
} else {
reject(new Error(`Upload failed: ${respInfo.statusCode}, ${respBody.error}`));
}
});
});
}
module.exports = {
uploadToQiniu,
};
route
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
const qiniuService = require('../service/qiniu');
module.exports = function (app) {
app.get('/health', (req, res) => {
return res.json({ message: 'OK', data: `Time Is ${new Date().toString()}` });
});
app.post('/upload', upload.single('image'), async (req, res) => {
try {
const fileBuffer = req.file.buffer;
const imageUrl = await qiniuService.uploadToQiniu(fileBuffer);
res.status(200).json({ imageUrl });
} catch (error) {
res.status(500).json({ error: 'Upload failed', message: error.message });
}
});
};
main.js
const router = require('./router');
const express = require('express');
const logger = require('./utils/logger');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const PORT = 3001;
router(app);
const server = http.createServer(app);
app.set('port', PORT);
server.listen(PORT, '0.0.0.0');
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
logger.log('warn', 'warning! listen address is in used~!');
server.close(function () {
process.exit();
});
} else {
logger.log('error', {
type: 'server error',
message: err.message,
stack: err.stack,
});
}
});
server.on('listening', () => {
const host = server.address().address;
const port = server.address().port;
logger.log('info', `app listening at http://${host}:${port}`);
});