2019-01-03


  
const Koa = require('koa')
const static = require('koa-static')
const path = require('path')
const router = require('koa-router')()
const multer = require('koa-multer');
const fs = require('fs')

const asyncUploadFtp = require('./upload')

const app = new Koa()

let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log(file);
    const des = path.join(__dirname, './upload')
    // 判断目录是否存在
    if(!fs.existsSync(des)){
      //创建目录
      fs.mkdirSync(des)
    }
    cb(null, des)
  },
  filename: function (req, file, cb) {
    //文件名
    let ext = file.originalname.substring(file.originalname.lastIndexOf('.'));
    let fileName = file.originalname.substring(0, file.originalname.lastIndexOf('.'))
    cb(null, fileName+ Date.now()+ext)
  }
})
let upload = multer({
  storage: storage
})

router.post('/upload', upload.single('file'), async (ctx, next) => {
  console.log(ctx.req.body);
  await asyncUploadFtp()
  ctx.body = {
      filename: ctx.req.file.filename //返回文件名 
    }
})


app.use(static(path.join(__dirname, './static')), {
  extensions: ['html']
})

app.use(router.routes()); //启动路由
app.use(router.allowedMethods());

app.listen(4455)
const FtpClient = require('ftp-client');
const _ = require('lodash');
const path = require('path')

var config = {
  host: '192.168.85.44',
  port: 21,
  user: 'ftp_inv_w',
  password: 'ftp_inv_w@123'
};


const base = '/upload';
const source = path.join(__dirname, `./${base}/**`);
const target = '/iams_data' + base;
const options = {
  logging: 'basic'
};
const upOption = {
    baseDir: base,
    overwrite: 'older'
}
module.exports = function asyncUploadFtp() {

  return new Promise((resolve, reject) => {
    var fct = new FtpClient(config, options);
    fct.connect(function () {
      fct.upload(source, target, upOption, (result) => {
        console.log(source,target);
        fct.ftp.end();
        if (_.isEmpty(result.errors) === false) {
          reject(result.errors);
        }
        resolve()
      })
    })
  })
};

你可能感兴趣的:(2019-01-03)