c# - 使图像可通过 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 中做到这一点?
解决方案
我终于想通了!您只需要制作一个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
推荐阅读
- sql - Oracle SQL FETCH NEXT 跨多行
- r - R - 基于前一行和其他列的新因子变量。优化Ifelse
- apache - Mod-Rewrite 使用转义字符串代替
- html - flexbox,第一个元素块换行
- microsoft-graph-api - 创建架构扩展会给出“名称包含无效字符”
- php - Mysql / PHP将空值上传到时间戳类型属性中
- html2canvas - html2canvas 截图后复选框不可见
- javascript - 如何在 Bootstrap 4.1 中单击汉堡按钮时在大屏幕上水平显示菜单项
- docker - 使用 yaml 在 Gitlab 中使用版本标记 Docker 映像
- vue.js - 在 Visual Studio Code 中使用 Vue 调试 NativeScript