【问题标题】:Save File Prompt instead of FileWriteAllBytes保存文件提示而不是 FileWriteAllBytes
【发布时间】:2013-04-19 15:50:22
【问题描述】:

长期潜伏者第一次海报。与.Net / Linq 合作了几年,所以我确定我在这里遗漏了一些东西。经过无数小时的研究,我需要帮助。 我的代码基于来自 https:http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3

的建议

以下代码当前将存储在 sql 数据库中的选定文件(pdf、doc、png 等)保存到 C:\temp。效果很好。我想更进一步。我可以让浏览器提示而不是自动将其保存到 c:\temp,以便他们可以将其保存到所需的位置。

  {     
   var getFile = new myDataClass();

   //retrieve attachment id from selected row
   int attachmentId = Convert.ToInt32((this.gvAttachments.SelectedRow.Cells[1].Text));

    //retrieve attachment information from dataclass (sql attachment table)
    var results = from file in getFile.AttachmentsContents
                       where file.Attachment_Id == attachmentId
                       select file;

    string writePath = @"c:\temp";

   var myFile = results.First(); 

   File.WriteAllBytes(Path.Combine(writePath, myFile.attach_Name), myFile.attach_Data.ToArray());
}

因此,我可以代替使用 File.WriteAllBytes 来获取从我的 linq 查询 (myFile) 返回的数据并将其传递给提示用户保存文件的东西吗?)。这个返回的对象可以与 response.transmitfile 一起使用吗?非常感谢。

【问题讨论】:

    标签: asp.net sql linq iqueryable savefiledialog


    【解决方案1】:

    只需使用BinaryWrite(myFile.attach_Data.ToArray()) 方法发送数据,因为它已经在内存中。

    但首先要适当设置标题,例如:

    "Content-Disposition", "attachment; filename="+myFile.attach_Name
    "Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    

    内容类型指导接收系统如何处理文件。这里有更多MS Office content types。如果在存储数据时它们是已知的,那么内容类型也应该被存储。

    另外,由于文件内容是响应中唯一需要的数据,因此请在 BinaryWrite 之前调用 Clear 并在 BinaryWrite 之后调用 End

    【讨论】:

    • 我开枪了!一旦我打开下载的文件,它就损坏了。我已经尝试过使用 docx 和 doc。出于测试目的,我保留了 File.WriteAllBytes 代码,如果我从 c:\temp 打开文档,它们可以正常打开。所以我仍然缺少 Response.Write(myFile.attach_Data.ToArray());
    • 在寻求解决方案时,我将 Response.Write 更改为 Response.BinaryWrite。 doc 文件和 pdf 文件现在可以正常打开,但 docx 不太好。
    • 添加 Reponse.Clear() 和 Response.AddHeader() 这似乎确实可以解决问题。唯一的区别是我的内容类型被设置为附件,到目前为止打开 pdf、docx 和 doc 文件都没有问题。如果其他文件类型(如 XLS)引起问题,我可能需要进一步研究您在上面发布的内容类型。谢谢
    猜你喜欢
    • 2018-03-15
    • 1970-01-01
    • 2022-01-15
    • 2015-03-30
    • 1970-01-01
    • 2018-10-23
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多