testService.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const fs = require('fs');
  3. // node.js 路径操作对象
  4. const path = require('path');
  5. // 异步二进制 写入流
  6. const awaitWriteStream = require('await-stream-ready').write;
  7. // 管道读入一个虫洞。
  8. const sendToWormhole = require('stream-wormhole');
  9. const Service = require('./baseService');
  10. class TestService extends Service {
  11. tag() {
  12. return this.ctx.model.testModel;
  13. }
  14. async upload(filename) {
  15. const ctx = this.ctx;
  16. let stream;
  17. try {
  18. stream = await ctx.getFileStream();// 获取文件
  19. if (!filename) {
  20. // 新建一个文件名 = 文件名 + 时间 + 文件后缀
  21. filename = path.parse(stream.filename).name
  22. + Date.now() + path.extname(stream.filename)
  23. .toLocaleLowerCase();
  24. }
  25. // 文件生成绝对路径 this.app.config.defaultUploadPath
  26. // 放在服务器什么目录下/strong/images/info_admin/
  27. const target = path
  28. .join(this.app.config.defaultUploadPath, filename);
  29. // 生成一个文件写入 文件流
  30. const writeStream = fs.createWriteStream(target);
  31. // 异步把文件流 写入
  32. await awaitWriteStream(stream.pipe(writeStream));
  33. return this.app.config.defaultWritePathPre + filename;
  34. } catch (err) {
  35. ctx.logger.debug(err);
  36. // 如果出现错误,关闭管道
  37. await sendToWormhole(stream);
  38. return null;
  39. }
  40. }
  41. }
  42. module.exports = TestService;