【问题标题】:Why this action doesn't result in a file being downloaded? How to do that?为什么此操作不会导致文件被下载?怎么做?
【发布时间】:2019-12-16 17:55:06
【问题描述】:

我正在ASP.NET MVC3... 中编写程序我如何导出动态生成的.xml 文件以供下载?

我通过视图中的按钮调用导出例程:

@using (Html.BeginForm(FormMethod.Post))
{
    <div>
… 
        <input type="submit" value="Export to XML" class="btn btn-primary" style="background-color: green;" asp-action="Export" asp-controller="Manage" />
… 
    </div>

通过这个按钮,我想生成一个 XML 文件并打开一个下载另存为对话框以将其下载到本地计算机……

然后我在 ManageController 中有以下导出操作:

public IActionResult Export(IFormCollection form)
{
    … gathers form info and gets the table to be exported: oTable
    // export to .xml here!
    ExportXMLModel e = new ExportXMLModel();

    return (e.DoExportXML(oTable)); // Doesnt export...
    // sorry for the clumsy code…, but I'll write it better afterwards.
}

这里定义了DoExportXML(这里我创建了一个MemoryStream…):

public class ExportXMLModel
{
   public ActionResult DoExportXML(List<itemType> ol)
   {
       XMLDocType XMLdoc = new XMLDocType();

       … fills the XMLdoc object … 

       MemoryStream memoryStream = new MemoryStream();

       XmlSerializer xml = new XmlSerializer(typeof(XMLDocType));

       TextWriter writer = new StreamWriter(memoryStream);

       xml.Serialize(writer, XMLdoc);

       FileResult file = new FileResult(memoryStream.ToArray(), "text/xml", "myXmlFile.xml");

       writer.Close();

       return file;
   }
}

然后定义 FileResult 类:

public class FileResult : ActionResult
{
    public String ContentType { get; set; }
    public byte[] FileBytes { get; set; }
    public String SourceFilename { get; set; }

    public FileResult(byte[] sourceStream, String contentType, String sourceFilename)
    {
         FileBytes = sourceStream;
         SourceFilename = sourceFilename;
         ContentType = contentType;
    }
}

这不会导致文件被下载……

我怎样才能做出这样的回应?使用 ASP.NET MVC 还是使用 jQuery?

非常感谢您的任何回答。

【问题讨论】:

  • 你不应该构建自己的 FileResult,你应该使用built-in one

标签: c# jquery html asp.net-mvc


【解决方案1】:

.NET Framework Controller.File 和 .NET Core ControllerBase.File 提供了几个 FileResult 方法的抽象。两者都可以返回字节数组或流,并允许您定义内容类型和文件名。

只需进行一些修改,您的代码就可以正常工作。您不需要 FileResult 类(MS 已经完成了繁重的工作)。修改ExportXMLModel.DoExportXML 以返回一个字节数组(您将流转换为该数组,然后将其传递给您的自定义FileResult)。

那么你的控制器动作如下所示:

public IActionResult Export(IFormCollection form)
{
    … gathers form info and gets the table to be exported: oTable
    // export to .xml here!
    ExportXMLModel e = new ExportXMLModel();

    return File(e.DoExportXML(oTable), "text/xml", "myXmlFile.xml");
}

【讨论】:

  • 非常感谢内森。你的答案就是解决方案!
猜你喜欢
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多