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

 

效果:

相关推荐
刚子编程6 天前
从零开始:在 Windows 服务器上部署 Node.js 项目(小白实战教程)
服务器·nestjs·pm2·windowsserver·node.js部署·caddy反向代理
CSharp精选营6 天前
从零开始:在 Windows 服务器上部署 Node.js 项目(小白实战教程)
nestjs·pm2·windowsserver·node.js部署·caddy反向代理
晓杰'8 天前
从0到1实现Balatro游戏后端(8):Skip Blind与Tag奖励机制设计与实现
后端·websocket·typescript·项目实战·nestjs·状态管理·游戏服务器
小蜜蜂dry12 天前
nestjs实战-权限二:角色模块
前端·后端·nestjs
小蜜蜂dry12 天前
nestjs实战-权限一: 菜单模块
前端·后端·nestjs
妖孽白YoonA14 天前
xlt-token v1.0.0 正式发布:NestJS / Express 一包接入的 Token 鉴权库
后端·node.js·nestjs
晓杰'15 天前
从0到1实现Balatro游戏后端(7):Boss Blind与特殊规则实现
后端·websocket·typescript·node.js·游戏开发·项目实战·nestjs
晓杰'15 天前
从0到1实现Balatro游戏后端(6):Blind关卡状态设计与回合推进实现
后端·websocket·typescript·游戏开发·项目实战·nestjs·状态管理
晓杰'22 天前
从0到1实现Balatro游戏后端(5):得分计算与单局结算流程实现
后端·typescript·node.js·游戏开发·项目实战·nestjs·webscoket
向上的车轮23 天前
NestJS 的优秀替代框架——系统化选型指南(2026视角)
nestjs