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

 

效果:

相关推荐
用户5757303346245 天前
拒绝“明文”裸奔!NestJS + Bcrypt 打造企业级用户注册与异常防御体系
nestjs
yuanlaile15 天前
NestJS实战商城与云原生落地指南
云原生·nestjs·nestjs学习指南
小二李19 天前
DTO,DAO是什么?MVC是什么架构?
nestjs
Ticnix22 天前
NestJs--Prisma 7的安装与数据库配置(超完整)
前端·nestjs
小蜜蜂dry23 天前
nestjs实战-登录、鉴权(二)
前端·后端·nestjs
全栈王校长23 天前
Nest 文件上传 - 就是增强版的 el-upload
前端·后端·nestjs
小蜜蜂dry24 天前
nestjs实战-登录、鉴权(一)
前端·后端·nestjs
小蜜蜂dry24 天前
nestjs实战 - 拦截器,统一处理接口请求与响应结果
前端·后端·nestjs
当时只道寻常24 天前
NestJS + OpenAI 实现流式输出
openai·nestjs
dyb-dev25 天前
我是如何学习 NestJS 的
前端·nestjs·全栈