我一直在试图找出将存储在Sql Server数据库中的文件作为可用于Web应用程序的FILESTREAM
的最佳方法。
基本上,我有一个用Vue编写的Web应用程序,支持它的ASP.NET CORE WebApi,当用户上传图像(作为varbinary(max) FILESTREAM
存储在数据库中)时,用户应该能够在浏览器中查看图像。
我想用<img src="{url to image}"/>
所以问题是:如何从db中的记录中获取{url to image}
标记的img
。我需要它1.跨多个服务器工作,所以如果Web应用程序和数据库在不同的服务器上。 2.我需要url成为别名,以免放弃存储文件的文件夹结构。
如果有必要,我也会对如何处理文件存储的任何建议持开放态度。
谢谢。
如果它是一个小图像(低于5KiB),您可以使用Base64将原始数据编码为图像的内联data:
URI。
否则,您将需要编写仅提供图像数据的新Controller Action。请记住也要设置正确的内容类型。将记录键作为URI参数传递。
[Route("/record-images/{recordPrimaryKey}")]
public async Task<IActionResult> GetImage( Int32 recordPrimaryKey )
{
using( SqlConnection c = ... )
using( SqlCommand cmd = c.CreateCommand() )
{
cmd.CommandText = "SELECT ..."; // I assume the raw file data is returned through `SqlDataReader`. I assume that FILESTREAM is just a back-end storage concern.
using( SqlDataReader rdr = await cmd.ExecuteReaderAsync() )
{
if( !rdr.Read() ) return this.NotFound();
Byte[] imageData = rdr.GetBytes( 0 );
String contentType = rdr.GetString( 1 );
return this.File( imageData, contentType );
}
}
}