七牛nodejs sdk的补充说明


补完某些模糊不清的细节。

完整可用的demo(包括浏览器端代码)位于https://github.com/zxdong262/qiniu-nodejs-angularjs-demo

初始化环境

var qiniu = require('qiniu')
qiniu.conf.ACCESS_KEY = '{Your Access Key}'
qiniu.conf.SECRET_KEY = '{Your Secret Key}'

创建uploadtoken

var qs = require('querystring')

function ctreateUploadToken() {

    var bucketName = '{你的七牛空间名称}'
    var putPolicy = new qiniu.rs.PutPolicy(bucketName)

    //需要返回的数据指定callbackBody
    //更多参考 http://developer.qiniu.com/docs/v6/api/reference/security/upload-token.html
    var callbackBodyObj = {
      name: '$(fname)'
      ,hash: '$(etag)'
      ,imageInfo: '$(imageInfo)'
      ,fsize: '$(fsize)'
      ,key: '$(key)'
      ,ext: '$(ext)'
      ,bucket: '$(bucket)'
    }

    //指定返回数据的接口url: callbackUrl
    //本地开发环境如果不是七牛可以直接访问到的url, 比如localhost:4100//qiniu-callback
    //可以通过ngrok.com来代理
    //参考 https://github.com/zxdong262/qiniu-nodejs-angularjs-demo
    var callbackUrl = 'xxxxx.ngrok.io/qiniu-callback'
    //var callbackUrl = 'your-doamin.x/qiniu-callback'

    //转成字符串, 注意qs会把$转成 "%24", 得转回来
    var callbackBodyStr = qs.stringify(callbackBodyObj).replace(/\%24/g, '$')


    putPolicy.callbackUrl = callbackUrl
    putPolicy.callbackBody = callbackBodyStr

    //putPolicy更多参数参考 http://developer.qiniu.com/docs/v6/sdk/nodejs-sdk.html 上传策略


    return putPolicy.token()

}


//express
app.get('/upload-token', function(req, res) {

  //注意要命名为uptoken
  res.json({
    uptoken: ctreateUploadToken()
  })

})

//koa
app.get('/upload-token', function*(next) {

  //注意要命名为uptoken
  this.body = {
    uptoken: ctreateUploadToken()
  }

})

接收上传成功后返回的数据

//express
var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.post('/qiniu-callback', function(req, res) {

  var infoObject = req.body

  //数据形如:
  //{"name":"download.png","hash":"FoO0sxxxx9mFVKcVo4D3wUzHpWW","imageInfo":"{\"format\":\"png\",\"width\":200,\"height\":200,\"colorModel\":\"nrgba\"}","fsize":"3908","key":"FoO0slsknA9mFVKcVo4D3wffffWW","ext":".png","bucket":"xxxxxx"}

  //处理infoObject,加工存储到数据库等。。
  //do_something_to(infoObject)

  //返回, 之后七牛服务器会返回给浏览器端
  res.json(infoObject)

})

//koa
var bodyParser = require('koa-bodyparser')
app.use(bodyParser())

app.post('/qiniu-callback', function*(next) {

  var infoObject = this.request.body
  //处理infoObject,加工存储到数据库等。。
  //do_something_to(infoObject)
  //还可以验证是否合法
  //if(!validate(this)) return this.body = { error: '非法' }

  //返回, 之后七牛服务器会返回给浏览器端
  this.body = infoObject

})


//一个有限的验证
//from qiniu sdk
function hmacSha1(encodedFlags, secretKey) {
  /*
   *return value already encoded with base64
  * */
  var hmac = crypto.createHmac('sha1', secretKey)
  hmac.update(encodedFlags)
  return hmac.digest('base64')
}

function validate(ctx) {

  var code = ctx.get('Authorization')
  if(!/^QBox /.test(code)) return false

  var arr = code.slice(5).split(':')
  if(arr.length !== 2 || arr[0] !== qiniu.conf.ACCESS_KEY) return false

  //官方文档还有编码验证,很遗憾试了多种方式无法通过
  //如果您知道,求指导
  return true

  /*

    var data = ctx.path + '/n' + encodeURIComponent(JSON.stringify(body))
    
    return hmacSha1(data, setting.qiniu.secretKey) === arr[1]

  */

}