nodejs 使用七牛雲端儲存上傳檔案

triste發表於2019-02-16

[toc]

本文在最新qiniu sdk 開發只適用於0.4.6node 開發。
詳細關注: https://github.com/tstrilogy/…

在網上尋找了很多七牛雲端儲存的博文,也百度了許多。但是都不盡如人意,因此自個擼一個小示例。

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);
  })
})

相關文章