我调用一个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动作完全运行,但我在浏览器中收到以下错误:
加载资源失败:服务器响应状态为500(内部服务器错误)
MVC Action:
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");
}
调用MVC动作的Ajax代码:
function convertToPDF() {
window.location = '/Tracker/ConvertPathInfoToPDF?pInfo=null';
}