如何使 FileStream 文件可用于 Web 应用程序
How to make FileStream files available to a web app
我一直在努力找出使存储在 Sql 服务器数据库中的文件作为 Web 应用程序可用的 FILESTREAM
文件的最佳方法。
基本上,我有一个用 Vue 编写的 Web 应用程序,一个支持它的 ASP.NET CORE WebApi,当用户上传图像(作为 varbinary(max) FILESTREAM
存储在数据库中)时,用户应该可以在浏览器中查看图像。
我想使用 <img src="{url to image}"/>
所以问题是:如何从数据库中的记录中获取 img
标记的 {url to image}
。我需要它 1. 跨多个服务器工作,所以如果 Web 应用程序和数据库位于不同的服务器上。和 2. 我需要 url 作为别名,以免泄露存储文件的文件夹结构。
如有必要,我也乐于接受有关如何以不同方式处理文件存储的任何建议。
谢谢。
如果是小图片(小于 5KiB),您可以使用 Base64 将原始数据编码为图片的内联 data:
URI。
否则,您将需要编写一个仅提供图像数据的新控制器动作。记住也要设置正确的内容类型。将记录密钥作为 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 );
}
}
}
我一直在努力找出使存储在 Sql 服务器数据库中的文件作为 Web 应用程序可用的 FILESTREAM
文件的最佳方法。
基本上,我有一个用 Vue 编写的 Web 应用程序,一个支持它的 ASP.NET CORE WebApi,当用户上传图像(作为 varbinary(max) FILESTREAM
存储在数据库中)时,用户应该可以在浏览器中查看图像。
我想使用 <img src="{url to image}"/>
所以问题是:如何从数据库中的记录中获取 img
标记的 {url to image}
。我需要它 1. 跨多个服务器工作,所以如果 Web 应用程序和数据库位于不同的服务器上。和 2. 我需要 url 作为别名,以免泄露存储文件的文件夹结构。
如有必要,我也乐于接受有关如何以不同方式处理文件存储的任何建议。
谢谢。
如果是小图片(小于 5KiB),您可以使用 Base64 将原始数据编码为图片的内联 data:
URI。
否则,您将需要编写一个仅提供图像数据的新控制器动作。记住也要设置正确的内容类型。将记录密钥作为 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 );
}
}
}