0

好的,我设法将 DOCX 这个词上传到我的 SQL Server 数据库中的一varbinary (Max)列中。

我可以从数据库中检索 DOCX 并将其从 varbinary 转换回一个数组,并通过以下方式将其作为下载提供:

    Byte[] bytes = (Byte[])dt.Rows[0]["TD_DocFile"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = dt.Rows[0]["TD_DocContentType"].ToString();
    Response.AddHeader("content-disposition", "attachment;filename="
    + dt.Rows[0]["TD_DocTitle"].ToString());
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();

而不是下载文档,我更愿意在变量中使用它,所以我在其中交换占位符。

我试图找到一种将其转换为字符串的方法,或者我可以将它用于 docx,例如。

 DocX letter = this.document();

到目前为止我看到的最佳选择是文件流版本

public static MemoryStream databaseFileRead(string varID) {
    MemoryStream memoryStream = new MemoryStream();
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
        sqlQuery.Parameters.AddWithValue("@varID", varID);
        using (var sqlQueryResult = sqlQuery.ExecuteReader())
            if (sqlQueryResult != null) {
                sqlQueryResult.Read();
                var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
                sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
                //using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
                memoryStream.Write(blob, 0, blob.Length);
                //}
            }
    }
    return memoryStream;
}

但是我无法将二进制数组字节或内存流转换为 docx 可以理解的变量。也许我只是在寻找错误的对话。有人可以给我一个提示吗?

该字段是TD_DocContentType从数据库中调用的。我可以接受我在这种情况下的转换很弱。我看不出我做错了什么。需要一个新的想法。亲切的问候,雷内

4

1 回答 1

0

我找到了解决我的问题的方法。花了一段时间和更多的研究来做。我试图从错误的角度解决问题。

此解决方案从数据库中读取二进制字段并将其作为文件写入名为 doctemp 的内部 Web 文件夹。

私人无效下载(DataTable dt)

{
    var physicalPath = Server.MapPath("~\\doctemp\\{0}");
    string outputFileName = string.Format(physicalPath, dt.Rows[0]["TD_DocTitle"]);
    filename = outputFileName;

    Byte[] bytes = (Byte[])dt.Rows[0]["TD_DocFile"];
    File.WriteAllBytes(outputFileName, bytes);
}
于 2014-05-23T05:13:52.837 回答