You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS中向Cloudinary上传图片并限制大小与指定文件夹

实现方案

要添加图片大小限制(1MB)和指定Cloudinary文件夹的功能,只需在两个关键环节修改代码:

1. 限制图片大小(双重校验更安全)

方式一:通过Multer在服务器端提前拦截

在处理上传请求的控制器中,配置Multer拦截器时添加文件大小限制,同时可限制仅允许图片类型:

// profile.controller.ts
import { Controller, Post, Param, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ProfileService } from './profile.service';

@Controller('profile')
export class ProfileController {
  constructor(private readonly profileService: ProfileService) {}

  @Post(':id/upload-image')
  @UseInterceptors(FileInterceptor('file', {
    // 限制文件大小为1MB(1*1024*1024字节)
    limits: { fileSize: 1048576 },
    // 仅允许上传图片类型
    fileFilter: (req, file, cb) => {
      if (!file.mimetype.startsWith('image/')) {
        return cb(new BadRequestException('仅支持图片格式文件'), false);
      }
      cb(null, true);
    },
  }))
  async uploadProfileImage(@UploadedFile() file: Express.Multer.File, @Param('id') id: string) {
    return this.profileService.uploadProfileImage(file, id);
  }
}

方式二:在Cloudinary上传时二次校验

即使Multer拦截了,也可以在Cloudinary层面再次设置大小限制,避免绕过服务器端限制的情况:

2. 指定Cloudinary目标文件夹

修改CloudinaryService的uploadImage方法,在upload_stream中传入folder参数,指定你在Cloudinary媒体库中创建的文件夹名称:

// cloudinary.service.ts
import { Injectable } from '@nestjs/common';
import { UploadApiErrorResponse, UploadApiResponse, v2 } from 'cloudinary';
import toStream = require('buffer-to-stream');

@Injectable()
export class CloudinaryService {
  async uploadImage(
    fileName: Express.Multer.File,
  ): Promise<UploadApiResponse | UploadApiErrorResponse> {
    return new Promise((resolve, reject) => {
      const upload = v2.uploader.upload_stream(
        {
          // 替换为你的Cloudinary文件夹名称
          folder: 'user-profiles',
          // 二次限制文件大小为1MB
          max_file_size: 1048576,
          // 指定资源类型为图片
          resource_type: 'image',
        },
        (error, result) => {
          if (error) return reject(error);
          resolve(result);
        }
      );
      toStream(fileName.buffer).pipe(upload);
    });
  }
}

代码说明

  • Multer的限制会在文件到达服务器前就拒绝超大文件,节省带宽和服务器资源;
  • Cloudinary的max_file_size参数会在云端再次校验,确保上传到Cloudinary的文件符合要求;
  • folder参数指定后,上传的图片会自动存入你在Cloudinary媒体库中创建的对应文件夹,方便管理。

内容的提问来源于stack exchange,提问作者zackOverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:35:27