bigFileUpload.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Context } from 'koa';
  2. import config from '@config';
  3. import { FileUploaderServer } from '@utils/bigFileSlice';
  4. import CODE from '@utils/code';
  5. const fileUploader = new FileUploaderServer();
  6. const initUpload = async (ctx: Context): Promise<void> => {
  7. const { name } = ctx.query;
  8. const uploadId = await fileUploader.initFilePartUpload(name);
  9. ctx.body = ctx.$response({ uploadId });
  10. };
  11. const uploadPart = async (ctx:Context): Promise<void> => {
  12. const { buffer } = ctx.file;
  13. const { uploadId, partIndex } = ctx.request.body;
  14. if (!uploadId || uploadId === 'undefined') {
  15. ctx.status = 400;
  16. ctx.body = ctx.$response(null, '必填项参数缺失', false, CODE.MISS_PARAMS);
  17. }
  18. const {
  19. partFileMd5,
  20. partIndex: index
  21. } = await fileUploader.uploadPartFile(uploadId, partIndex, buffer);
  22. console.log({ partFileMd5, index });
  23. ctx.body = ctx.$response({ partFileMd5, index });
  24. };
  25. const finishUpload = async (ctx:Context): Promise<void> => {
  26. const { uploadId, name, md5 } = ctx.query;
  27. const { path: filePathOnServer } = await fileUploader
  28. .finishFilePartUpload(uploadId, name, md5);
  29. const suffixDir = config.bigFileUpload.suffixDir;
  30. const suffix = filePathOnServer.split(`/${suffixDir}/`)[1];
  31. ctx.body = ctx.$response({ path: suffix });
  32. };
  33. export default {
  34. initUpload,
  35. uploadPart,
  36. finishUpload
  37. };