为什么此操作不会导致文件下载?怎么做?

时间:2019-12-16 17:55:06

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

我正在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?

非常感谢您的回答。

1 个答案:

答案 0 :(得分:0)

.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");
}