簡體   English   中英

為什么此操作不會導致下載文件? 怎么做?

[英]Why this action doesn't result in a file being downloaded? How to do that?

我正在用ASP.NET MVC3...編寫程序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?

非常感謝您的任何答復。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM