使用FileTable和ASP.. NET c#(打开PDF格式)

本文关键字:打开 PDF 格式 FileTable ASP NET 使用 | 更新日期: 2023-09-27 18:12:37

当用户点击链接时,我试图在浏览器中打开PDF(或下载)PDF。我在SO(在c#/.net 4中打开FileTable文件)上发现了一个类似的问题,并试图在我的代码中实现答案,但没有任何运气。我真的只需要看到一个完整的例子,如何打开一个文件从FileTable在ASP。. NET/c# .

代码:

public FileResult Download(int? id)
{
    //start of my test code
    Document document = db.Documents.Find(id);
    string fileName;
    byte[] fileData;
    System.Guid path = document.DocumentPath;
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["FT_ConnectionString"].ConnectionString))
    {
        string sql = "SELECT TOP 1 file_stream, name, file_type, cached_file_size FROM FTAdvisoryOpinions WHERE stream_id = @SID";
        using (var command = new SqlCommand(sql, connection))
        {
            command.Parameters.Add("@SID", SqlDbType.UniqueIdentifier).Value = path;
            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                if (reader.Read())
                {
                    //file_stream = 0
                    //name = 1
                    //file_type = 2
                    //cached_file_size = 3
                    long fileSize = reader.GetInt64(3); //think this might be wrong
                    string contentType = reader.GetString(2);

                    fileData = reader.GetBytes(0, 2, fileData, 0, fileSize);  //says I have some invalid arguments
                    fileName = reader.GetString(1);
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                    return File(fileData, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
                }
                else
                {
                    connection.Close();
                }
            }
            return null; // just returning null here til I figure it out.
        }
    }
}

使用FileTable和ASP.. NET c#(打开PDF格式)

不是通过GetInt64读取存储字段上的blob大小,实际上可以从对GetBytes的调用中获得该信息。在传递大小为0的地方调用该方法一次。结果将告诉您数据的大小。然后使用一个足够大的数组再次调用该方法,以容纳实际读取的数据。

主要的事情是,GetBytes不返回字节,它返回的信息有多少字节还没有被读取,你在数据结构中传递它应该读取字节作为一个参数。

PS:如果你的数据很大,你可能想要用最大缓冲区大小增量读取流。但你应该没有,至少对于初学者来说。

PPS:作为题外,我想提一下,你真的不需要显式地关闭你的连接,因为using块会释放它,而释放它会关闭它。