温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

NodeJS如何使用云服务器存储上传文件

发布时间:2021-07-24 11:22:18 来源:亿速云 阅读:200 作者:小新 栏目:web开发

这篇文章主要介绍NodeJS如何使用云服务器存储上传文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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如何使用云服务器存储上传文件”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI