cloudinary上传文件找不到文件

cloudinary upload file cannot find file

我想使用 cloudinary 上传文件,但无法正常工作。文件字符串参数应该是什么?

@Injectable()
export class CloudinaryService {
  async uploadImage(
    file: Express.Multer.File,
    id: string,
  ): Promise<UploadApiResponse | UploadApiErrorResponse> {
    return new Promise((resolve, reject) => {
      v2.uploader.upload(
        file.filename,
        { public_id: id, folder: 'business', resource_type: 'auto' },
        (error, result) => {
          if (error) return reject(error);
          resolve(result);
        },
      );
    });
  }
}

这是文件对象

{
  fieldname: 'DirectorsDetails',
  originalname: 'Eddy - Information about directors.xlsx',
  encoding: '7bit',
  mimetype: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  buffer: <Buffer 50 4b 03 04 14 00 08 08 08 00 14 2a be 52 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 78 6c 2f 64 72 61 77 69 6e 67 73 2f 64 72 61 77 69 6e 67 31 ... 5072 more bytes>,
  size: 5122
}

尝试使用 upload_stream 函数。

import { FileUpload } from 'graphql-upload';

export class CloudinaryService {
  async uploadImage(
    file: FileUpload,
  ): Promise<UploadApiResponse | UploadApiErrorResponse> {
    return new Promise((resolve, reject) => {
      const upload = v2.uploader.upload_stream((error, result) => {
        if (error) return reject(error);
        resolve(result);
      });

      file.createReadStream().pipe(upload);
    });
  }
}

file.filename 仅当您在磁盘上存储多个文件时才会填充。也许 file.originalname 就是您正在寻找的 属性。

试试看是否有帮助:

调整multer以使用内存存储在后期获取缓冲区

// app.module.ts
import { MulterModule } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';

@Module({
  imports: [
    ...
    MulterModule.register({
      storage: memoryStorage(), // use memory storage for having the buffer
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

将缓冲区转为流并bootstrap将其上传

import { Injectable } from '@nestjs/common';
import { UploadApiErrorResponse, UploadApiResponse, v2 } from 'cloudinary';
import { Readable } from 'stream';

@Injectable()
export class CloudinaryService {
  async uploadImage(
    file: Express.Multer.File,
  ): Promise<UploadApiResponse | UploadApiErrorResponse> {
    return new Promise((resolve, reject) => {
      const upload = v2.uploader.upload_stream((error, result) => {
        if (error) return reject(error);
        resolve(result);
      });
      Readable.from(file.buffer).pipe(upload); // covert buffer to readable stream and pass to upload
    });
  }
}

如果你想先将它保存到本地目录,你可以这样做,但你需要通过 fs.createReadStream 从路径读取文件以制作它的流并将其上传到 cloudinary。


如果你做不出来,我可以上传一个例子到github,你对照一下。