【发布时间】:2018-07-05 14:40:03
【问题描述】:
我们使用一些 Web 表单成功地在我们的 SQL Server(varbinary 列)中添加了 word 文档,然后,我们希望我们的一些员工能够下载它们。
我们有一些代码可以显示它,但有时它会显示(在我的本地环境中),有时它不会显示,但是当它投入生产时。所以,我们只想下载它,不管它是否打开(如果你没有安装 Word),我们只想下载它,比如“另存为.. 。“ 功能。因为在我的本地环境中它运行良好,但是当它上线到 IIS 服务器时,我们无法检索文件(我猜是因为它会自动打开 WORD)。
这是检索它的代码。
public string showDoc(int id, int numRef)
{
string fileName = Path.GetTempFileName() + ".docx";
Db.Open();
string cuerito = "select doc from tbl_references where [userId]=@id and [refNum]=@numRef";
SqlCommand command = new SqlCommand(cuerito, base.Db);
command.Parameters.AddWithValue("@id", id);
command.Parameters.AddWithValue("@numRef", numRef);
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
int size = 1024 * 1024;
byte[] buffer = new byte[size];
int readBytes = 0;
int index = 0;
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
while ((readBytes = (int)dr.GetBytes(0, index, buffer, 0, size)) > 0)
{
fs.Write(buffer, 0, readBytes);
index += readBytes;
}
}
}
}
Db.Close();
return fileName;
}
在 C# 中有没有办法做到这一点?不显示,只从 SQL Server 下载?
EB。
【问题讨论】:
-
IIUC,你已经在读文件了,为什么不能写到别的地方呢?那不是“下载”吗?
-
完全不清楚你想在这里做什么。
-
问题是,当它投入生产(IIS 服务器)时,这个解决方案不起作用。它只适用于我的本地环境,因为它会自动打开 Word(这是我的猜测)。你知道的,比如“另存为...”功能,下载它(无论我是否安装了 Word)。
-
在提供的代码中哪里有对 Word 的引用?
-
“不起作用”是什么意思?究竟会发生什么错误或意外行为?上面的所有代码都是从二进制字段中读取一些数据并将其写入一个流,该流被写入服务器上的磁盘。在您提供文件以供下载之前,无需将文件保存到磁盘,您可以直接将数据流式传输到客户端 - 如果您使用谷歌搜索,有大量示例和包含此过程的工作示例的先前问题。它们适用于任何文件,这些都不是 Word 文件所特有的。而且这些都与互操作无关——我将删除该标签。
标签: c# asp.net sql-server webforms