富贵资源网 Design By www.hznty.com

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使用七牛云存储上传文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com