【解决问题】nestjs传输文件到指定路径

问题:

FileInterceptor只有req,file,cb三个参数,req无法解析body formdata

大体思路:

发送两次请求,第一次发送相对路径,如果没有这个文件夹则创建一个然后暂时保存路径,第二次就发送文件到指定路径

部分代码:

js 复制代码
  //设置当前路径
   @Post('setpath')
   setpath(@Body() body:any){
    try {
       let path2 = join(__dirname,'../files')
       path2=join(path2,body.userid)
       path2=join(path2,body.path)
      if (!existsSync(path2)) {
        console.log('创建文件夹:', body.userid,path2);
        mkdirSync(path2, { recursive: true });
      }
      currentpath=path2
    } catch (error) {
      console.error('创建文件夹失败:', error);
    }
  }
  
   //上传文件
  @Post('ulfile')
  @UseInterceptors(FileInterceptor('file', {
    storage: diskStorage({
      destination: (  req, file, cb) => {
          // 假设 currentpath 是一个类的属性
          console.log(currentpath, 'destinationPath');
          const destinationPath = currentpath; // 提取到局部变量
       
          // 确保 destinationPath 已经被初始化
          if (!destinationPath) {
            return cb(new Error('当前路径未定义'), '');
          }
          cb(null, destinationPath);
      },
      filename: (req, file, cb) => {
        const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('');
        return cb(null, `${randomName}${extname(file.originalname)}`);
      },
    }),
  }))
  ulfile(@UploadedFile() file,@Session() session) {

    return  {status:200, message: 'File uploaded successfully', file};
  }

 

效果:

相关推荐
倾颜2 小时前
NestJS 核心概念梳理:从 Module、Controller 到 Guard、Interceptor
后端·node.js·nestjs
薛定谔的算法11 小时前
NestJS:让 Node.js 后端告别「野路子」
后端·node.js·nestjs
To_OC3 天前
从一行入口代码啃透 NestJS:工厂模式、装饰器和依赖注入是怎么串起来的
后端·设计模式·nestjs
__zRainy__4 天前
Node.js Web 框架选型指南:从 Express 到 Hono 的全景对比
前端·node.js·express·koa·nestjs·egg·fastify
Darling噜啦啦4 天前
NestJS 全栈 CRUD 实战:从 Module 拆分到 RESTful 七大装饰器,彻底搞懂后端接口工程
nestjs
嘟嘟07174 天前
从入口到 CRUD:用 NestJS 的模块化与装饰器思想读懂一个后端应用
后端·typescript·nestjs
想要成为糕糕手4 天前
🚀 NestJS 完全入门指南: Module/Controller/Service讲解 + 实战 CRUD
后端·nestjs
想要成为糕糕手4 天前
🏭 设计模式之工厂模式:从蜜雪冰城到 NestJS,把「new」外包出去
后端·nestjs
小月土星4 天前
用设计哲学的眼光重新审视 NestJS——一个 AI 应用后端的思考
nestjs