0

我已成功将文件上传到我的 SQL Server 数据库中。我可以将信息带回 GridView。我无法弄清楚如何创建一个超链接来实际打开文件。

4

4 回答 4

2

您需要创建一个 URL 来处理图片并将 DB 内容返回到响应流中。正如在SQL 星期六 #26上发生的那样,我有一个演示文稿正好展示了这一点。您可以从链接中下载我的幻灯片,进入演示 2,然后在 lotOfPictures 解决方案中找到 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 标志,它将返回一个真正的流,因此页面在返回之前不会将整个图像加载到内存中。对于高性能服务器,您应该使用异步操作,如ASP.NET 2.0 中的异步页面中所述。

于 2009-10-23T19:21:11.430 回答
0

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

于 2009-10-23T17:33:16.703 回答
0

通常你会使用你的服务器端代码来发送适当的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');
于 2009-10-23T17:51:46.510 回答
0

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

于 2009-10-23T19:08:28.490 回答