How can I work with sending a certain number of images in Loopback4?

23 Views Asked by At

I need my API to receive three files, with one file it is easy for me, because I don't have to work with the use of multipart/form-data, I need those three files to be updated where it corresponds (using the corresponding repository).

What is wrong with my API?

  @post('uploads/rentalDataFiles/{id}')
  @response(200, {
    description: 'Save the VIN, Voucher and Registration Card images of the rental data.',
    content: {
      'multipart/form-data': {
        schema: {
          type: 'object',
          properties: {
            vinFile: {
              type: 'string',
            },
            voucherFile: {
              type: 'string',
            },
            registrationCardFile: {
              type: 'string',
            },
          },
        },
      },
    },
  })
  async fileUpload(
    @requestBody({
      description: 'The input of file upload function',
      required: true,
      content: {
        'multipart/form-data': {
          // Skip body parsing
          'x-parser': 'stream',
          schema: {
            type: 'object',
            properties: {
              vinFile: {
                type: 'string',
                format: 'binary',
              },
              voucherFile: {
                type: 'string',
                format: 'binary',
              },
              registrationCardFile: {
                type: 'string',
                format: 'binary',
              },
            },
          },
        },
      },
    })
    request: Request,
    @inject(RestBindings.Http.RESPONSE)
    responseEndpoint: Response,
    @param.path.string('id')
    rentalDataId: number
  ): Promise<object | false> {
    const RENTAL_DATA_PATH_ABSOLUTE = path.join(__dirname, UploadFilesKeys.RENTAL_DATA_IMAGE_PATH);

    const files = ['vinFile', 'voucherFile', 'registrationCardFile'];
    const updateObject = {};

    for (const file of files) {
      const optionFile: FileUploadOptions = {
        storePath: RENTAL_DATA_PATH_ABSOLUTE,
        fieldname: file,
        request,
        responseEndpoint,
        acceptedExt: UploadFilesKeys.IMAGE_ACCEPTED_EXT,
      };

      const responseRentalData = await this.serviceUpload.storeFilesToPath(optionFile);
      if (responseRentalData) {
        const filename = responseEndpoint.req.file?.filename;
        let updateObject: { [key: string]: string } = {};
        if (filename) {
          let fullPath = path.join(RENTAL_DATA_PATH_ABSOLUTE, filename);
          updateObject[file] = fullPath;
        }
      }
    }

    await this.rentalDataRepository.updateById(rentalDataId, updateObject);
    return updateObject;
  }

This is the method of service I use:

public storeFilesToPath(options: FileUploadOptions): Promise<object> {
    return new Promise<object>((resolve, reject) => {
      const storage = this.getMulterStorageConfig(options.storePath);

      const upload = multer({
        storage: storage,
        fileFilter: function (req, file, callback) {
          const ext = path.extname(file.originalname).toUpperCase();
          if (options.acceptedExt.includes(ext)) {
            return callback(null, true);
          }
          return callback(new HttpErrors[400]('This format file is not supported.'));
        },
      }).fields([{ name: 'vinFile' }, { name: 'voucherFile' }, { name: 'registrationCardFile' }]);

      upload(options.request, options.responseEndpoint, (err: string) => {
        if (err) {
          reject(err);
        }
        resolve(options.responseEndpoint);
      });
    });
  }

I have the next error: Request POST /uploads/rentalDataFiles/5 failed with status code undefined. Error: Unexpected end of form at Multipart._final

0

There are 0 best solutions below