账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    nestjs 图片转发
    95
    0

    nest 转发图片到其他服务一直不成功,请大佬看看哪里有问题?

    // controller
     @UseInterceptors(FileInterceptor('file'))
      async uploadImage(@UploadedFile() file) {
        return await this.irsService.uploadImage(file);
      }
    // service
      async uploadImage(file) {
        let formData = new FormData()
        formData.append("file",file)
        return await this.httpService.post(
          'url/xxx/xxx',
          formData,
        );
      }
    // 从前端拿到的file
    { 
         fieldname: 'file',
         originalname: '下载.jpeg',
         encoding: '7bit',
         mimetype: 'image/jpeg',
         buffer:
          <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 84 00 09 06 07 13 12 10 15 10 13 13 15 15 15 15 17 18 15 15 16 15 15 15 15 15 10 ... >,
    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 辭痛的溫柔の 普通会员 1楼

      在NestJS中,如果你想要转发图片,通常不是直接转发而是通过读取源图片并重新上传到目标服务器或者返回给客户端。以下是一个基本示例,假设你正在从一个文件系统或数据库中获取图片并将其作为响应返回给客户端:

      ```typescript // 假设你有一个专门处理图片的服务或控制器 import { Controller, Get, Res } from '@nestjs/common'; import * as fs from 'fs';

      @Controller('images') export class ImagesController {

      @Get(':imageName') async getImage(@Res() res, @Param('imageName') imageName: string) { // 根据名称从你的存储位置读取图片 const imageBuffer = fs.readFileSync(./uploads/${imageName});

      // 设置响应头
      res.set({
        'Content-Type': 'image/jpeg', // 或其他图片类型如 'image/png'
      });
      
      // 返回图片数据
      return res.send(imageBuffer);
      

      } } ```

      如果你需要将接收到的图片转发到另一个API服务,你需要首先读取图片,然后使用HTTP客户端(如axios或node-fetch)将其发送到目标服务器:

      ```typescript import { HttpService } from '@nestjs/axios'; import { Injectable } from '@nestjs/common'; import * as fs from 'fs';

      @Injectable() export class ImageForwardService { constructor(private httpService: HttpService) {}

      async forwardImage(imageName: string) { // 读取图片 const imageBuffer = fs.readFileSync(./uploads/${imageName});

      // 使用HTTP客户端发送图片
      await this.httpService.post(
        'http://target-server.com/api/upload',
        imageBuffer,
        {
          headers: {
            'Content-Type': 'image/jpeg', // 根据实际情况调整
          },
        },
      ).toPromise();
      

      } } ```

      请注意,这些代码仅供参考,实际应用中可能需要根据你的具体需求和环境进行调整。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部