app.js 2.3 KB
Newer Older
1 2 3 4 5 6
const Koa = require('koa');
const path = require('path');
const router = require('koa-router')();
const koaBody = require('koa-body');
const static = require('koa-static');
const cors = require('koa2-cors');
7
const fs = require('fs-extra');
8 9
const app = new Koa();

10 11 12 13
const uploadUrl = 'http://localhost:3001/static/upload';

fs.ensureDir(path.join(__dirname, 'static/upload'));

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
app.use(cors());

app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFieldsSize: 20 * 1024 * 1024,
      multipart: true,
    },
  })
);

router.get('/', (ctx) => {
  ctx.type = 'html';
  const pathUrl = path.join(__dirname, '/static/upload.html');
  ctx.body = fs.createReadStream(pathUrl);
});

const uploadFilePublic = function (ctx, files, flag) {
  const filePath = path.join(__dirname, '/static/upload/');
  let fileReader, fileResource, writeStream;

  const fileFunc = function (file) {
    fileReader = fs.createReadStream(file.path);
    fileResource = filePath + `/${file.name}`;

    writeStream = fs.createWriteStream(fileResource);
    fileReader.pipe(writeStream);
  };
  const returnFunc = function (flag) {
    console.log(flag);
    console.log(files);
    if (flag) {
      let url = '';
      for (let i = 0; i < files.length; i++) {
        url += uploadUrl + `/${files[i].name},`;
      }
      url = url.replace(/,$/gi, '');
      ctx.body = {
        url: url,
        code: 0,
V
vben 已提交
55
        message: 'upload Success!',
56 57 58 59 60
      };
    } else {
      ctx.body = {
        url: uploadUrl + `/${files.name}`,
        code: 0,
V
vben 已提交
61
        message: 'upload Success!',
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
      };
    }
  };
  if (flag) {
    for (let i = 0; i < files.length; i++) {
      const f1 = files[i];
      fileFunc(f1);
    }
  } else {
    fileFunc(files);
  }

  if (!fs.existsSync(filePath)) {
    fs.mkdir(filePath, (err) => {
      if (err) {
        throw new Error(err);
      } else {
        returnFunc(flag);
      }
    });
  } else {
    returnFunc(flag);
  }
};

router.post('/upload', (ctx) => {
  let files = ctx.request.files.file;
  if (files.length === undefined) {
    uploadFilePublic(ctx, files, false);
  } else {
    uploadFilePublic(ctx, files, true);
  }
});

app.use(static(path.join(__dirname)));

app.use(router.routes()).use(router.allowedMethods());

app.listen(3001, () => {
  console.log('server is listen in 3001');
});