0

当用户单击链接时,我正在尝试在浏览器中打开 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.
        }
    }
}
4

1 回答 1

1

您实际上GetInt64可以从对GetBytes. 在传递 0 大小的位置调用该方法一次。结果将告诉您数据的大小。然后使用一个足够大的数组再次调用该方法以保存数据以实际读取数据。

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

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

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

于 2014-07-11T20:46:02.757 回答