NodeJS使用七牛云存储上传文件的方法
程序员文章站
2022-04-29 09:00:57
1-准备工作
确认安装node和npm
安装 qiniu,formidable,express模块
npm install --save qiniu form...
1-准备工作
确认安装node和npm
安装 qiniu,formidable,express模块
npm install --save qiniu formidable
[x] 导入模块
let qiniu = require('qiniu'), formidable = require('formidable'), express = require('express'), router = express.router();
2-服务器端的云存储操作
2-1文件上传
router.post('/qiniu', function (req, res, next) { let bucket = 'myblog', key = '', form = formidable.incomingform(), token, putpolicy; form.uploaddir = path.join(__dirname, '../../', 'public/img/upload'); form.keepextensions = true form.parse(req, function (err, fields, files) { if (err) { console.log(err); } key = files.mypic.path.split(path.sep).pop(); putpolicy = new qiniu.rs.putpolicy(bucket + ':' + key) //设置回调 // putpolicy.callbackurl = 'http://localhost:81/test/callback' // putpolicy.callbackbody = 'filename=$(fname)&filesize=$(fsize)' token = putpolicy.token() console.log('token', token) let extra = new qiniu.io.putextra() qiniu.io.putfile(token, key, files.mypic.path, extra, function (err, ret) { if (err) { console.log(err) } console.log('ret', ret); res.json({ token: token, ret: ret, files: files, fields: fields }) }) }) })
文件下载
router.get('/download/:key', function (req, res, next) { let url = 'http://xxxx.bkt.clouddn.com/' + req.params.key, policy = new qiniu.rs.getpolicy(); console.log(url); res.json({url: policy.makerequest(url)}) })
文件获取
router.get('/info/:key', function (req, res, next) { let bucket = 'myblog', key = req.params.key, client = new qiniu.rs.client(); client.stat(bucket, key, (err, ret) => { if (err) { console.log(err); } res.json(ret); }) })
总结
以上所述是小编给大家介绍的nodejs使用七牛云存储上传文件的方法,希望对大家有所帮助
上一篇: AngularJS页面传参的5种方式