我一直在试图找出将文件存储在 Sql Server 数据库中的最佳方法 FILESTREAM
可用于网络应用程序。
基本上,我有一个用 Vue 编写的 Web 应用程序,一个支持它的 ASP.NET CORE WebApi,当用户上传图像(作为 varbinary(max) FILESTREAM
存储在数据库中)时,用户应该能够查看浏览器中的图像。
我想使用 <img src="{url to image}"/>
所以问题是:我如何获得 {url to image}
对于img
来自数据库中记录的标签。我需要它 1. 跨多个服务器工作,因此如果 Web 应用程序和数据库位于不同的服务器上。 2.我需要将 url 设为别名,以免泄露存储文件的文件夹结构。
如有必要,我也愿意接受有关如何以不同方式处理文件存储的任何建议。
谢谢。
最佳答案
如果它是一个小图像(低于 5KiB),您可以通过 Base64 将原始数据编码为图像的内联 data:
URI。
否则,您需要编写一个仅提供图像数据的新 Controller 操作。请记住也要设置正确的内容类型。将记录 key 作为 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-server - 如何使 FileStream 文件可供 Web 应用程序使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937867/