【问题标题】:Transmit generated XML file without saving to disk传输生成的 XML 文件而不保存到磁盘
【发布时间】:2010-12-25 09:18:12
【问题描述】:

我有一个大型网络表单应用程序,我希望允许用户导出他们的数据,以防他们不想一次完成整个表单。然后当他们返回时,他们可以导入数据并从中断的地方继续。

这样做的原因是客户端要求的一部分是不使用数据库。

我已经创建了一个包含所有表单数据的 XML 文件,但我希望客户端能够下载该 XML 文件,而无需应用程序将其保存到服务器,即使是暂时的。

是否可以创建 XML 文件并通过流/附件将其传输到客户端而不将其保存到磁盘?

我正在使用 C# Asp.net

【问题讨论】:

    标签: c# xml forms dynamic download


    【解决方案1】:

    你可以写到 HttpResponse:

            HttpResponse response = HttpContext.Current.Response;
    
            string xmlString = "<xml>blah</xml>";
            string fileName = "ExportedForm.xml";
    
            response.StatusCode = 200;
    
            response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            response.AddHeader("Content-Transfer-Encoding", "binary");
            response.AddHeader("Content-Length", _Buffer.Length.ToString());
    
            response.ContentType = "application-download";
            response.Write(xmlString);
    

    【讨论】:

    • 请注意,我专门使用“application-download”的 ContentType 而不是更准确的 mime 类型“application/xml”或“text/xml”。这是为了解决 IE6 中“content-disposition”标头中的文件名不用于默认“另存为”文件名的问题。
    【解决方案2】:

    你没有提到你使用的是什么服务器技术,但一般来说:

    1. 在内存中创建 xml 文档,并将其写入响应流。
    2. 将 Content-Type 标头更改为 text/xml
    3. 将 Content-disposition 标头更改为 attachment; filename=data.xml;

    一些链接: http://en.wikipedia.org/wiki/MIME#Content-Disposition

    【讨论】:

      【解决方案3】:

      查看 MemoryStream。

      http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx

      您应该能够将 XML 存储在内存中,然后通过 HTTP 请求或您想要的任何方式将其传送到您的客户端。

      【讨论】:

        【解决方案4】:
            HttpResponse response = HttpContext.Current.Response;
        
            string xmlString = "<xml>blah</xml>";
            string fileName = "ExportedForm.xml";
        
            response.StatusCode = 200;
        
            response.AddHeader("content-disposition", "attachment;
        

        文件名="+文件名); response.AddHeader("Content-Transfer-Encoding", "binary"); response.AddHeader("内容长度", _Buffer.Length.ToString());

            response.ContentType = "application-download";
            response.Write(xmlString);
        

        但它会将所有页面内容保存到文件中

        【讨论】:

        • 我解决了这个问题。但是现在我对国家符号有疑问。如何在 Response 中设置编码?
        • 也解决了。 Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1257");
        【解决方案5】:

        是的。在 PHP 中它看起来像这样:

        header("Content-type: text/xml");
        $headerText = "Content-disposition: attachment; filename=file.xml";
        header($headerText); 
        echo $your_XML_contents;
        exit;
        

        【讨论】:

        • 糟糕,我忘了说我使用的是 C# Asp.net
        • 然后多注意 mlsteeves 的评论,同样的事情,但他的语言不可知:D
        猜你喜欢
        • 1970-01-01
        • 2016-07-22
        • 2015-12-14
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 2013-12-26
        • 2018-09-14
        相关资源
        最近更新 更多