Created
September 14, 2018 06:11
-
-
Save chiwent/19469c4cb1e16d2e369318be00273276 to your computer and use it in GitHub Desktop.
上传文件到七牛
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 将文件上传到七牛 | |
// from: https://www.ntweet.net/article/59c21ef05d46937dd8491992 | |
//qiniuConfig.js | |
exports.conf = { | |
accessKey: 'xxx', | |
secretKey: 'xxx', | |
bucket: 'xxx' // 要上传的空间 | |
} | |
// upload.js | |
let qiniu = require('qiniu') | |
let qiniuConfig = require('./qiniuConfig') | |
let config = new qiniu.conf.Config({ | |
zone: qiniu.zone.Zone_z2, | |
useHttpsDomain: true, | |
useCdnDomain: true | |
}) | |
let localFile = './img-0.png' | |
// 上传到七牛后保存的文件名 | |
let key = 'img-' + Date.now() + '.png' | |
// 构建上传策略函数 | |
function getUploadToken () { | |
let options = { | |
scope: qiniuConfig.conf.bucket, | |
returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}' | |
} | |
let mac = new qiniu.auth.digest.Mac(qiniuConfig.conf.accessKey, qiniuConfig.conf.secretKey) | |
let putPolicy = new qiniu.rs.PutPolicy(options) | |
return putPolicy.uploadToken(mac) | |
} | |
function uploadFile (fileKey, localFile) { | |
// 生成上传 Token | |
let token = getUploadToken() | |
let formUploader = new qiniu.form_up.FormUploader(config) | |
let putExtra = new qiniu.form_up.PutExtra() | |
// 文件上传 | |
formUploader.putFile(token, fileKey, localFile, putExtra, function (respErr, | |
respBody, respInfo) { | |
if (respErr) { | |
throw respErr | |
} | |
if (respInfo.statusCode === 200) { | |
console.log(respBody) | |
} else { | |
console.log(respInfo.statusCode) | |
console.log(respBody) | |
} | |
}) | |
} | |
uploadFile(key, localFile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment