koa 七牛上传问题。。求大神支招
发布于 7 年前 作者 847039386 3377 次浏览 来自 问答
const qn     = require('qn');
const path = require('path')
const fs = require('fs')
const Busboy = require('busboy')
const utility = require('utility');



function Koa2_Upload(config){
  config = config || {}
  this.uploadPath = config.uploadPath || './public/upload/common/';
  this.qn_access = config.qn_access || null;
}
//文件无则创建
Koa2_Upload.prototype.mkdirsSync = function(dirname){
  if (fs.existsSync( dirname )) {
    return true
  } else {
    if (this.mkdirsSync( path.dirname(dirname)) ) {
      fs.mkdirSync( dirname )
      return true
    }
  }
}
//公共解析
Koa2_Upload.prototype.busboy = function(ctx,callbck) {
    let that = this;
    let req = ctx.req
    let res = ctx.res
    let busboy = new Busboy({headers: req.headers})
    return new Promise((resolve, reject) => {
       // console.log('文件上传中...')
       let infoJson = {
         success: false,   //成功
         message: '',      //信息
         data: null,       //返回的路径
         fields : { }      //返回字段
       }
       // 解析请求文件事件
       busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
          let primise = callbck(fieldname, file, filename, encoding, mimetype)
          primise.then(function(data){
            infoJson.success = true;
            infoJson.message = '文件上传成功';
            infoJson.data = data;
            resolve(infoJson)
          }).catch(function(err){
            reject(err)
          })
       })
       busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
           infoJson.fields[fieldname] = val
       });
       // 解析错误事件
       busboy.on('error', function(err) {
         reject(err)
       })
       req.pipe(busboy)
     })
}
//本地上传方法
Koa2_Upload.prototype.local_upload = function(file,filename) {
  const that = this;
  const newFilename = utility.md5(filename + String((new Date()).getTime())) + path.extname(filename);
  const defult_upload_url = this.default_upath;
  const upload_path = path.normalize(that.uploadPath)
  this.mkdirsSync( upload_path )
  const filePath    = path.join(upload_path, newFilename);   //构造出整个文件的绝对路径
  const fileUrl     = path.join(that.uploadPath, newFilename);  //这是相对路径,用于上传后访问用
  return new Promise((res ,rej) => {
    file.on('end', function () {
      res({
        url : fileUrl,
        filename : newFilename
      })
    });
    file.pipe(fs.createWriteStream(filePath));
  })
};
//七牛上传方法
Koa2_Upload.prototype.qn_upload = function(file){
  let that = this;
  return new Promise((resolve ,reject) => {
    let buf = Buffer.alloc(0);
    file.on('data', function(data) {
       buf = Buffer.concat([ buf ,data]);
    });
    file.on('end', function(){
      qn.create(that.qn_access).upload(buf,{},function(err,data){
        err ? reject(err) : resolve(data)
      })
    })
  })
}
//处事方法 返回 promise
Koa2_Upload.prototype.init = function(ctx) {
  let that ,busboy;
  that = this
  return that.busboy(ctx ,function(fieldname, file, filename, encoding, mimetype){
    let promise;
    if(that.qn_access){
      promise = that.qn_upload(file)
    }else{
      promise = that.local_upload(file,filename)
    }
    return promise;
  })
}

module.exports = Koa2_Upload;

各位大神 ,我想问下 为啥在七牛上传的时候出现了问题。。如果直接 qn.create(that.qn_access).upload(file)就报错了,但是file本身就是可读流啊 而qn也支持流文件上传。。。现在这方法压根没解决想要实现的效果。想要得到的效果是用户直接通过服务器上传到七牛,而不是web上传到七牛,也不是弄个缓存路径在去传七牛在删文件。。有没有老师给支支招啊。?

2 回复

我就是保存在本地,上传了在删的 [T.T~]

@NanShanJi 但是那样的话执行速度变慢。比如一个2g的MP4,要先下载下来在上传。。我想直接用户给七牛。。我这个现在跟你那个没啥区别 只不过没删文件。。而nodeclub源码的异步上传就是这么写的。。我没测试过 不过他那应该没问题。。所以我搞不懂

回到顶部