首页 > 解决方案 > 使图像可通过 HTTP 访问

问题描述

例如,我需要制作一个文件,以便c:\users\user\documents\screenshot.png可以从网络访问并拥有自己的 url: content.efolio.com/p/123/screenshot.png

目前我将文件路径存储在数据库表中。当请求到来时,文件被转换为 Base64 字符串并在 JSON 中发送。

public class Project 
{
  public int Id { get; set; }

  public string Name { get; set; }

  public string PhotoEncoded { get; set; }

  public string Description { get; set; } 

  public void AddPhoto(byte[] content, string fileFormat) 
  {
    PhotoEncoded = string.Format("data:image/{0};base64,{1}", 
      fileFormat.Substring(1,fileFormat.Length-1), 
      Convert.ToBase64String(content)
    );
  }
}

但我只想发送网址。问题是我不知道如何通过 url 使文件可用。我如何在 ASP.NET Core 中做到这一点?

标签: c#asp.net-core

解决方案


我终于想通了!您只需要制作一个ContentController将为单个文件提供服务并使用以下File()方法的方法ControllerBase

[ApiController] 
[Route("[controller]")]
public class ContentController : ControllerBase
{
   [HttpGet("project/{id}/{fileName}")] 
   public async Task<IActionResult> GetProjectThumbnail(int id, string fileName)
   {
       try
       {
           return File(await _projects.GetThumbnailAsync(id, fileName), "image/jpeg");
       }
       catch (Exception ex)
       {
           return StatusCode((int)HttpStatusCode.InternalServerError, new ErrorResponse(ex));
       }
   }
   //...
}

之后,我可以通过 url 访问缩略图:https://efolio.com/content/project/1003/1.jpg


推荐阅读