【解决问题】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};
  }

 

效果:

相关推荐
前端付豪11 小时前
Nest 项目小实践之前端注册登陆
前端·node.js·nestjs
Mr_li3 天前
NestJS 集成 TypeORM 的最优解
node.js·nestjs
前端付豪4 天前
Nest 项目小实践之注册登陆
前端·node.js·nestjs
Mr_li4 天前
手摸手,教你如何优雅的书写 NestJS 服务配置
node.js·nestjs
Jiude5 天前
AI 全栈时代的工程化护栏:Vben-Nest 让 Mock 契约落地成真实后端
前端·后端·nestjs
折七6 天前
NestJS 用了两年,我换了这个
typescript·node.js·nestjs
NEXT0613 天前
深度解析 JWT:从 RFC 原理到 NestJS 实战与架构权衡
前端·typescript·nestjs
明月_清风15 天前
从“搬运工”到“指挥官”:通过 IoC 容器重塑你的后端思维
后端·nestjs
UIUV17 天前
实现RAG功能学习笔记
react.js·langchain·nestjs
None32120 天前
【NestJs】如何使用Prisma实现@Transactional装饰器开启事务并且跨Service传递
nestjs