【问题标题】:how to display images from nestjs server to Angular如何从nestjs服务器显示图像到Angular
【发布时间】:2022-08-12 01:35:50
【问题描述】:

我正在尝试将图像从 Angular 端上传到 NestJs。其实这是我上传的一本书。我上传了带有描述和图片的书。现在我可以上传图片,并且可以将图片路径存储为参考书。现在的情况是,当我从 Angular 端上传一本书时,它使用 imagepath 发布这本书,并且图像也存储在 NestJs 文件夹中,但我无法显示带有它的图像的书。这本书在前端显示,但没有在后端引用和保存的图像。所以请告诉我如何显示图像,这将是一个巨大的问题。

前端结果(没有图片的书)

Anguar 前端代码 .ts

 export class BooksComponent implements OnInit {
      BookForm = new FormGroup({
        _id: new FormControl(\'\'),
        name: new FormControl(\'\'),
        author: new FormControl(\'\'),
        price: new FormControl(\'\'),
        genres_name: new FormControl(\'\'),
        coverimage: new FormControl(\'\'),
      });
      results?: Book[] = [];
      searchedText: string = \'\';
      constructor(
        private readonly apiService: ApiService,
        private router: Router
      ) {}
    
      ngOnInit() {
        this.apiService.getallbooks().subscribe((data) => {
          this.results = data;
    
          console.log(this.results);
        });
      }

我将图像存储在 \"./assets\" 文件夹中的 NestJs 后端代码。我什至尝试对图像发出@Get 请求,但没有帮助。

@ApiTags(\'Book Cover Images\')
@Controller(\'images\')
export class ImagesController {
  static imageUrl: string;
  constructor(private readonly bookservice: BooksService) {}

  @Post(\'upload\')
  @UseInterceptors(
    FileInterceptor(\'file\', {
      storage: diskStorage({
        destination: \'./assets/\',
        filename: (req, file, cb) => {
          const filename: string = Array(10)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join(\'\');
          return cb(null, `${filename}${extname(file.originalname)}`);
        },
      }),
    }),
  )
  async uploadFile(@UploadedFile() file: Express.Multer.File, @Request() req) {
    console.log(file);
    return this.imageUrl(file);
  }

  private imageUrl(file: Express.Multer.File) {
    ImagesController.imageUrl = `./assets/${file.originalname}`;
    return ImagesController.imageUrl;
  }


// @Get(\'bookimages/:imagename\')
  // findbookimages(
  //   @Param(\'imagename\') imagename,
  //   @Res() res,
  // ): Observable<Object> {
  //   return of(res.sendFile(join(process.cwd(), \'.assets/\' + imagename)));
  // }
}

前端 html 代码。我正在获取所有信息,但不是图像,这里我提供src in img tag to display images

<div class=\"grid\" *ngFor=\"let result of results\">
    <div class=\"blog-card spring-fever\" style=\"padding: 0.5rem; z-index: 100\">
      <img
        class=\"image\"
        src=\"http://localhost:3000/{{ result.coverimage }}\"
        alt=\"\"
        height=\"400px\"
        width=\"250px\"
        style=\"border: 1px solid red\"
      />

      <div class=\"title-content\">
        <h3>
          <a href=\"#\">{{ result?.name }}</a>
        </h3>
        <div class=\"intro\">
          <h5>
            <a>Author<b>:</b>&nbsp;{{ result?.author }}</a>
          </h5>

          <h5>
            <a>Price<b>:</b>&nbsp;Rs{{ result?.price }}</a>
          </h5>
          <h5>
            <a>Genre<b>:</b>&nbsp;{{ result?.genres_name }}</a>
          </h5>
        </div>
      </div>

这是来自后端的书的信息

当我尝试这样src=\"{{result.coverimage}}\"[src]=\"result.coverimage\" 时,我得到错误localhost:4200/assets/imagename not found(404)。好吧,这很明显!因为没有这样的路径,所以 4200 是 Angular 的。但是我正在将图像上传到位于localhost:3000/assets/ 的后端资产文件夹中,我们总是将文件上传到后端以从数据库中获取动态方法

    标签: html angular file nestjs


    【解决方案1】:

    在帖子的突出显示部分中,您询问如何显示图像,即您怀疑问题出在前端。但是,提供的上下文中缺少部分。在html 魔法发生的那一行(img 标签src 属性)。

    在那里,您在results 对象下插入了一个名为coverimage 的属性。从您在前端屏幕截图中的后端响应中,我们看不到 coverimage 中的内容。如果它是一个文档的id,那么它不会被正确解析。 src 属性接受: APNGAVIFGIFJPEGPNGSVGWebP。或base64(这里似乎不是这种情况)。

    当您拥有带有 acceptable supported formats 之一的图像时,如 MDN 中所述,您可以通过以下方式将该属性映射到 src 属性

    1-字符串插值:

    <img src="{{imagePath}}" />
    

    2-属性绑定:

    <img [src]="imagePath" />
    

    第二种方式更受欢迎,但都可以正常工作。

    PS:建议填充alt="" 属性是最佳实践和可访问性

    【讨论】:

    • coverimage 属性是 book 类的字符串类型属性。在后端,coverimage 属性保存上传的图像的路径。因此,根据我的理解,前端的coverimage under the result object 应该访问图像,因为图像的路径已存储,或者类似的东西。还有什么方法可以知道我从后端coverimage 属性中得到了什么? ,正如您告诉我的那样,我们不知道来自后端的内容。
    • 我已经用一些新信息和屏幕截图更新了我的问题,请注意它们。
    • 好的,前端的路径映射是正确的,但 URL 的正确格式指向不存在的东西。正如您已经提到自己的那样,资产/图像在不同的 PORT 下提供,即服务器地址。确保您的后端服务器 localhost:3000 已启动并正在运行,并且您可以在服务器和客户端都启动时访问您的图像
    • 那是我无法访问图像的问题,这就是我在这里的原因。只需告诉我您需要哪段或部分代码来理解问题。因为我被困在这里很久了。后端或前端我将提供所有代码。
    【解决方案2】:

    如果您像我一样努力显示来自服务器的图像,或者您正在努力处理来自 NestJs 的数据。那么这可能对你有用,因为它对我有用。

    所以在我的情况下我有一个书籍清单,每本书都有其图像的路径。我正在使用ngFor 并将图像src 设置为路径。这是正确的方法。但是图像不可见,网络将图像显示为text/html 类型。这里的实际问题不是type,实际问题是在我的URL。我在NestJs 服务器中有一个名为assets 的文件夹,预设在root,我已经设置了路径对于图像(在 NestJs 文件上传代码中),像这样./assets/。这也是设置目标文件夹的正确方法。我能够在浏览器中看到像 http://localhost:3000/imagename.png 这样的图像,这意味着我的服务器配置为通过根 URL 服务/提供我的图像,这就是我可以访问它们的原因 @987654330 @。但是我的api 以包含./assets/ 的格式返回图像。

    所以用下面的代码

    <div *ngIf="result.coverimage">
              <img
                class="image"
                src="http://localhost:3000/{{ result.coverimage }}"
                alt=""
                height="400px"
                width="250px"
                style="border: 1px solid red"
              />
            </div>
    

    我假设我正在像这样http:localhost:3000/imagename.png 那样点击网址。但实际上 Angular 看到的是这样的 URL http:localhost:3000/./assets/imagename.png。和这是注意正确的 URL 格式.网址不适用于.,。另外因为我的服务器是在root 下配置的,这个urlhttp;//localhost:3000/assets/imagename.png 也是错误的。而root 意味着,无论root 设置什么,在您的服务器的端口号之后可以直接访问。示例http://localhost:YourServerPortNumber/TheThing_Set_at_Root

    所以这个问题的解决方案如下

    src="http://localhost:3000/{{
                  result.coverimage.replace('./assets/', '')
                }}"
    

    对于上面的.replace('./assets/', ''),我们将删除./assets/ 并将其替换为'' 空白空间。所以现在 URL 是这种格式http://localhost:3000/imagename.png

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      相关资源
      最近更新 更多