FileService.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import path from 'path';
  2. import fs from 'fs-extra';
  3. const uploadUrl = 'http://localhost:3300/static/upload';
  4. const filePath = path.join(__dirname, '../static/upload/');
  5. fs.ensureDir(filePath);
  6. export default class UserService {
  7. async upload(ctx, files, isMultiple) {
  8. let fileReader, fileResource, writeStream;
  9. const fileFunc = function (file) {
  10. fileReader = fs.createReadStream(file.path);
  11. fileResource = filePath + `/${file.name}`;
  12. console.log(fileResource);
  13. writeStream = fs.createWriteStream(fileResource);
  14. fileReader.pipe(writeStream);
  15. };
  16. const returnFunc = function (flag) {
  17. if (flag) {
  18. let url = '';
  19. for (let i = 0; i < files.length; i++) {
  20. url += uploadUrl + `/${files[i].name},`;
  21. }
  22. url = url.replace(/,$/gi, '');
  23. ctx.body = {
  24. url: url,
  25. code: 0,
  26. message: 'upload Success!',
  27. };
  28. } else {
  29. ctx.body = {
  30. url: uploadUrl + `/${files.name}`,
  31. code: 0,
  32. message: 'upload Success!',
  33. };
  34. }
  35. };
  36. console.log(isMultiple, files.length);
  37. if (isMultiple) {
  38. for (let i = 0; i < files.length; i++) {
  39. const f1 = files[i];
  40. fileFunc(f1);
  41. }
  42. } else {
  43. fileFunc(files);
  44. }
  45. fs.ensureDir(filePath);
  46. returnFunc(isMultiple);
  47. }
  48. }