sql-server - 如何使 FileStream 文件可供 Web 应用程序使用

标签 sql-server asp.net-core filestream file-storage

我一直在试图找出将文件存储在 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/

相关文章:

C++文件流问题

android-sqlite - 通过从断言复制数据库文件在 Room 中使用预填充的数据库

sql - 通过 SQL 中的层次结构进行计算

sql - 如何使用TSQL按组获取日期差异统计

SQL Server 根据另一列求和特定行数

angular - Microsoft.AspNetCore.SpaTemplates 不会安装

c# - 如何使 Razor 页面仅在开发中可用?

sql-server - 在 SQL 中对大数据使用聚集索引与非聚集索引

javascript - 如何在搜索栏中获取项目的详细信息?

c# - 在同一个 FileStream 中读取和覆盖