2016-07-02 23 views
4

我称之为创建内存PDF文件的MVC操作。我想在完成操作后立即返回文件并下载。如何调用MVC操作来下载PDF文件?

Ajax代码调用MVC行动

function convertToPDF() { 
     $.ajax({ 
      url: "/Tracker/ConvertPathInfoToPDF", 
      type: "GET", 
      data: JSON.stringify({ 'pInfo': null }), 
      dataType: "json", 
      traditional: true, 
      contentType: "application/json; charset=utf-8", 
      success: function (data) { 

      }, 
      error: function() { 
       alert("Unable to call /Tracker/ConvertPathInfoToPDF"); 
      } 
     }); 
    } 

MVC行动

public FileResult ConvertPathInfoToPDF(PositionInfo[] pInfo) 
    { 
     MemoryStream fs = new MemoryStream(); 
     //FileStream fs = new FileStream(@"C:\Test.pdf", FileMode.Create, FileAccess.Write, FileShare.None); 
     Rectangle rec = new Rectangle(PageSize.A4); 
     Document doc = new Document(rec); 
     PdfWriter writer = PdfWriter.GetInstance(doc, fs); 
     doc.Open(); 
     doc.Add(new Paragraph("Hamed!")); 
     doc.Close(); 

     return File(fs, System.Net.Mime.MediaTypeNames.Application.Octet, "Test.pdf"); 
    } 

的MVC动作compeletly运行,但我收到以下错误在浏览器中:

加载资源失败:th E服务器500(内部服务器错误)的状态

+1

的[我可以如何呈现可能的复制从MVC控制器下载的文件?](http://stackoverflow.com/questions/730699/how-can-i-present-a-file-for-download-from-an-mvc-controller) –

回答

4

MVC行动回应:

public FileResult ConvertPathInfoToPDF(PositionInfo[] pInfo) 
    { 
     MemoryStream fs = new MemoryStream(); 
     Rectangle rec = new Rectangle(PageSize.A4); 
     Document doc = new Document(rec); 
     PdfWriter writer = PdfWriter.GetInstance(doc, fs); 
     doc.Open(); 
     doc.Add(new Paragraph("Hamed!")); 
     doc.Close(); 

     byte[] content = fs.ToArray(); // Convert to byte[] 

     return File(content, "application/pdf", "Test.pdf"); 
    } 

Ajax代码调用MVC操作:

function convertToPDF() { 
     window.location = '/Tracker/ConvertPathInfoToPDF?pInfo=null'; 
    }