files.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 } = 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) {
  20. dirs.push(catalog);
  21. }
  22. const saved = await this.saveFile(rootPath, dirs, stream);
  23. const uri = `${rootUrl}/${dirs.join('/')}/${saved.fileName}`;
  24. ctx.body = { errcode: 0, errmsg: 'ok', id: saved.id, name: saved.fileName, uri };
  25. }
  26. async saveFile(rootPath, dirs, stream) {
  27. const ctx = this.ctx;
  28. const ext = extname(stream.filename).toLowerCase();
  29. const name = moment().format('YYYYMMDDHHmmss');
  30. // TODO: 检查根路径是否存在,不存在则创建
  31. ctx.logger.debug('rootPath: ', rootPath);
  32. if (!fs.existsSync(rootPath)) {
  33. ctx.logger.debug('create dir: ', rootPath);
  34. fs.mkdirSync(rootPath);
  35. }
  36. // TODO: 检查分级目录是否存在,不存在则创建
  37. for (let i = 0; i < dirs.length; i++) {
  38. const p = `${rootPath}${sep}${dirs.slice(0, i + 1).join(sep)}`;
  39. if (!fs.existsSync(p)) {
  40. fs.mkdirSync(p);
  41. }
  42. }
  43. const filePath = `${rootPath}${sep}${dirs.join(sep)}${sep}`;
  44. const fileName = `${name}${ext}`;
  45. const writeStream = fs.createWriteStream(filePath + fileName);
  46. try {
  47. await awaitWriteStream(stream.pipe(writeStream));
  48. } catch (err) {
  49. await sendToWormhole(stream);
  50. throw err;
  51. }
  52. return { filePath, fileName, id: name };
  53. }
  54. }
  55. module.exports = FilesController;