代码之家  ›  专栏  ›  技术社区  ›  Scott and the Dev Team

如何从SQL Server数据库检索文件?

  •  0
  • Scott and the Dev Team  · 技术社区  · 15 年前

    我已成功将文件上载到我的SQL Server数据库中。我可以把信息带回到网格视图中。我不知道如何创建超链接来实际打开文件。

    4 回复  |  直到 15 年前
        1
  •  2
  •   Remus Rusanu    15 年前

    您需要创建一个处理图片并将db内容返回到响应流的URL。就像发生在 SQL Saturday #26 我做了一个展示。您可以从链接中下载我的幻灯片,进入演示2,在lotsofpictures解决方案中,您将找到picture.aspx.cs,这正是您所要求的:

    using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
    
                    SqlCommand cmd = new SqlCommand(
    @"SELECT picture 
    FROM resized_pictures 
    WHERE picture_id = @id
    AND picture_size = @size;", conn);
                    cmd.Parameters.AddWithValue("@id", pictureId);
                    cmd.Parameters.AddWithValue("@size", size);
    
                    using (SqlDataReader rdr = cmd.ExecuteReader(
                        CommandBehavior.SequentialAccess))
                    {
                        if (rdr.Read())
                        {
                            Response.ContentType = "image/jpeg";
                            byte[] bytes = new byte[1024];
                            long offSet = 0;
                            int countRead = (int) rdr.GetBytes(
                                0, offSet, bytes, 0, 1024);
                            while (countRead > 0)
                            {
                                Response.OutputStream.Write(bytes, 0, countRead);
                                offSet += countRead;
                                countRead = (int)rdr.GetBytes(
                                    0, offSet, bytes, 0, 1024);
                            }
                        }
                    }
                }
    

    谜题的重要部分是传递给sqlcommand阅读器的SequentialAccess标志,它将返回一个真正的流,因此在返回之前页面不会在内存中加载整个图像。对于高性能服务器,您应该使用异步操作,如中所述 Asynchronous Pages in ASP.NET 2.0 .

        2
  •  0
  •   Scott W    15 年前

    我自己也没有尝试过,但是如何将数据流到本地文件系统上的临时文件中,然后提供指向该临时文件的链接?

        3
  •  0
  •   jjclarkson Andy Rose    15 年前

    通常,您将使用服务器端代码发送适当的 headers ,然后只是回响内容。

    从PHP手册:

    // We'll be outputting a PDF
    header('Content-type: application/pdf');
    
    // It will be called downloaded.pdf
    header('Content-Disposition: attachment; filename="downloaded.pdf"');
    
    // The PDF source is in original.pdf
    readfile('original.pdf');
    
        4
  •  0
  •   jmaresca    15 年前

    如果文件存储在数据库中,则可能将其存储为博客或字节数组。在超链接单击事件中,需要将字节数组传递到流中,并使用流编写器创建文件。然后执行文件。