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

 

效果:

相关推荐
牧码岛4 天前
服务端之NestJS请求解析体系、从HTTP报文到参数注入的工程化实践、控制器方法、装饰器、Headers、Query、Param、Body、Req
typescript·nestjs
小蜜蜂dry5 天前
nestjs学习 - 管道(pipe)
前端·nestjs
小蜜蜂dry5 天前
nestjs学习 - 拦截器(intercept)
前端·nestjs
小蜜蜂dry7 天前
nestjs学习 - 守卫
前端·nestjs
xiaoxue..9 天前
前后端双令牌认证(Access Token + Refresh Token)全方案实现:安全与体验兼得
前端·后端·web安全·面试·typescript·nestjs
helloweilei12 天前
NestJS系列(3)- Provider(提供者)
nestjs·全栈
helloweilei12 天前
NestJS系列(2)- 控制器(Controller)
nestjs·全栈
helloweilei12 天前
NestJS系列(1)- nestjs简介及项目初始化
nestjs·全栈
刘晓飞13 天前
nestjs的类为控制器(Controller)
nestjs
onebyte8bits13 天前
NestJS 系列教程(十五):缓存体系设计 —— Redis、接口缓存与缓存三大问题解决方案
数据库·redis·后端·缓存·nestjs