使用nodejs上传图片到七牛报错
在本地开发是ok的,部署到服务器之后在生成token的时候报错
TypeError: Key must be a buffer
上传代码如下:
const qiniu = require('qiniu');
const bucket = 'my-bucket-name';
const qiniuCallbackUrl = 'http://api.mysite.com/qiniu';
const qiniuCallbackBody = {
name: '$(fname)',
hash: '$(etag)',
imageInfo: '$(imageInfo)',
key: '$(key)',
imgUrl: `${qiniuHost}/$(key)`
}
qiniu.conf.ACCESS_KEY = process.env.QINIU_AK;
qiniu.conf.SECRET_KEY = process.env.QINIU_SK;
Img.newImg = function * () {
let body = this.request.body;
let parts = parse(this);
let part;
let localPath = path.join(os.tmpdir(), Math.random().toString());
let stream = fs.createWriteStream(localPath);
let key, token;
while ((part = yield parse(this))) {
// let stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
part.pipe(stream);
key = part.filename;
token = uptoken(bucket, key);
let res = yield uploadFile(token, key, localPath);
this.body = res;
}
}
function uptoken(bucket, key) {
let scope = bucket + ":" + key;
let putPolicy = new qiniu.rs.PutPolicy(scope);
putPolicy.callbackUrl = qiniuCallbackUrl;
putPolicy.callbackBody = qs.stringify(qiniuCallbackBody).replace(/\%24/g, '$');
return putPolicy.token(); // 这行报错 TypeError: Key must be a buffer
}
function uploadFile(uptoken, key, localFile) {
return new Promise((resolve, reject) => {
let extra = new qiniu.io.PutExtra();
qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
if(!err) {
// 上传成功, 处理返回值
resolve(ret);
} else {
// 上传失败, 处理返回代码
reject(err);
}
});
})
}
上传图片的代码是参照koa example里面写的,感觉上传到七牛云的逻辑不能写在while里面,但是在外面又访问不到文件名,我想把文件名当做key 传到七牛。
请各路大神帮我看看哪里写错了
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论