How to to return an image with Web API Get method

前端 未结 4 1814
自闭症患者
自闭症患者 2020-12-01 08:57

I need to return an image with a Web API Get method. The code below seems to work fine except that I get this message in the Fiddler\'s ImageView window, \"This response is

4条回答
  •  离开以前
    2020-12-01 09:53

    This is the way I get image from API in my project. I share for whom concern.

    Image content save to Images folder in server and image name saved to Database.

    [Route("api/dashboard/GetImage")]
    public byte[] GetImage(int componentId)
    {
                using (var dashboardService = new DashboardService())
                {
                    var component = dashboardService.GetImage(componentId);
                    var context = HttpContext.Current;
                    string filePath = context.Server.MapPath("~/Images/" + component.ImageName);
                    context.Response.ContentType = "image/jpeg";
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            fileStream.CopyTo(memoryStream);
                            Bitmap image = new Bitmap(1, 1);
                            image.Save(memoryStream, ImageFormat.Jpeg);
    
                            byte[] byteImage = memoryStream.ToArray();
                            return byteImage;
                        }
                    }
                }
    }
    

    Get image content in Angular

    this.dashboardService.getImage(this.componentId)
        .subscribe((blob: any) => {
          let objectURL = 'data:image/jpeg;base64,' + blob;
          this.imageUrl = this.sanitizer.bypassSecurityTrustUrl(objectURL);;
    });
    

提交回复
热议问题