files.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. const moment = require('moment');
  4. const { sep, extname } = require('path');
  5. const fs = require('fs');
  6. const awaitWriteStream = require('await-stream-ready').write;
  7. const sendToWormhole = require('stream-wormhole');
  8. const assert = require('assert');
  9. class FilesController extends Controller {
  10. async upload() {
  11. const { ctx, app } = this;
  12. const { appid, catalog, item } = ctx.params;
  13. assert(appid);
  14. const stream = await ctx.getFileStream();
  15. ctx.logger.debug(stream);
  16. const rootPath = `${app.config.cdn.repos_root_path}`;
  17. const rootUrl = `${app.config.cdn.repos_root_url}`;
  18. const dirs = [ appid ];
  19. if (catalog && catalog !== '_') {
  20. const subs = catalog.split('_');
  21. dirs.push(...subs);
  22. }
  23. const saved = await this.saveFile(rootPath, dirs, stream, item);
  24. const uri = `${rootUrl}/${dirs.join('/')}/${saved.fileName}`;
  25. ctx.body = { errcode: 0, errmsg: 'ok', id: saved.id, name: saved.fileName, uri };
  26. }
  27. async saveFile(rootPath, dirs, stream, name) {
  28. const ctx = this.ctx;
  29. const ext = extname(stream.filename).toLowerCase();
  30. // TODO: 指定文件名或者按时间生成文件名
  31. // const name = moment().format('YYYYMMDDHHmmss');
  32. if (!name) name = moment().format('YYYYMMDDHHmmss');
  33. // TODO: 检查根路径是否存在,不存在则创建
  34. ctx.logger.debug('rootPath: ', rootPath);
  35. if (!fs.existsSync(rootPath)) {
  36. ctx.logger.debug('create dir: ', rootPath);
  37. fs.mkdirSync(rootPath);
  38. }
  39. // TODO: 检查分级目录是否存在,不存在则创建
  40. for (let i = 0; i < dirs.length; i++) {
  41. const p = `${rootPath}${sep}${dirs.slice(0, i + 1).join(sep)}`;
  42. if (!fs.existsSync(p)) {
  43. fs.mkdirSync(p);
  44. }
  45. }
  46. const filePath = `${rootPath}${sep}${dirs.join(sep)}${sep}`;
  47. const fileName = `${name}${ext}`;
  48. const writeStream = fs.createWriteStream(filePath + fileName);
  49. try {
  50. await awaitWriteStream(stream.pipe(writeStream));
  51. } catch (err) {
  52. await sendToWormhole(stream);
  53. throw err;
  54. }
  55. return { filePath, fileName, id: name };
  56. }
  57. }
  58. module.exports = FilesController;