【问题标题】:Working with FileTable and ASP.NET C# (Open a PDF)使用 FileTable 和 ASP.NET C#(打开 PDF)
【发布时间】:2014-07-11 19:24:05
【问题描述】:

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

代码:

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.
        }
    }
}

【问题讨论】:

    标签: c# sql sql-server asp.net-mvc filetable


    【解决方案1】:

    您实际上可以通过调用GetBytes 获取此信息,而不是通过GetInt64 读取存储字段上的blob 大小。在传递 0 大小的位置调用该方法一次。结果将告诉您数据的大小。然后再次调用该方法,使用一个足够大的数组来保存数据以实际读取数据。

    主要的是GetBytes 不返回字节,它返回关于还有多少字节要读取的信息,并且你传入它应该读取字节的数据结构作为参数。

    PS:如果您的数据很大,您可能希望以最大缓冲区大小增量读取流。但是你应该没问题,至少对于初学者来说。

    PPS:顺便说一句,我想提一下,您实际上并不需要明确关闭连接,因为 using 块会释放它,而释放它会关闭它。

    【讨论】:

      猜你喜欢
      • 2012-12-07
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多