imageHandleService.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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('egg').Service;
  10. class ImageHandleService extends Service {
  11. async upload(filename) {
  12. const ctx = this.ctx;
  13. const stream = await ctx.getFileStream();// 获取文件
  14. const fileNameT = stream.filename;
  15. const fileType = fileNameT.split('.')[fileNameT.split('.').length - 1].toLowerCase();
  16. if (fileType === 'png' || fileType === 'jpg' || fileType === 'jpeg') {
  17. if (ctx.request.headers['content-length'] / 1024 < 1024) { // 上传文件大小限制
  18. // let stream;
  19. try {
  20. if (!filename) {
  21. // 新建一个文件名 = 文件名 + 时间 + 文件后缀
  22. filename = path.parse(stream.filename).name
  23. + Date.now() + path.extname(stream.filename)
  24. .toLocaleLowerCase();
  25. }
  26. // TODO 修改成OSS -CH (已完成)
  27. // OSS (STS) Bucket
  28. await this.ctx.oss.get('bucket1').putStream(this.app.config.defaultWriteAliOSSPath + filename, stream);
  29. return this.app.config.defaultWritePathPre + filename;
  30. } catch (err) {
  31. ctx.logger.debug(err);
  32. // 如果出现错误,关闭管道
  33. // await sendToWormhole(stream);
  34. return null;
  35. }
  36. } else {
  37. return null;
  38. }
  39. } else {
  40. return null;
  41. }
  42. }
  43. // 上传操作手册,限制只能为docx的格式
  44. async uploadOperationManual(filename) {
  45. const ctx = this.ctx;
  46. const stream = await ctx.getFileStream();// 获取文件
  47. const fileNameT = stream.filename;
  48. const fileType = fileNameT.split('.')[fileNameT.split('.').length - 1];
  49. if (fileType === 'docx') {
  50. try {
  51. if (!filename) {
  52. // 新建一个文件名 = 文件名 + 时间 + 文件后缀
  53. filename = path.parse(stream.filename).name
  54. + Date.now() + path.extname(stream.filename)
  55. .toLocaleLowerCase();
  56. }
  57. // TODO 修改成OSS -CH (已完成)
  58. // OSS Bucket
  59. await this.ctx.oss.get('bucket1').putStream(this.app.config.operationManualPath + filename, stream);
  60. return this.app.config.defaultWriteFilePathPre + filename;
  61. } catch (err) {
  62. ctx.logger.debug(err);
  63. return null;
  64. }
  65. } else {
  66. return null;
  67. }
  68. }
  69. }
  70. module.exports = ImageHandleService;