2012-09-24 131 views
0

我要生成一个PDF文档,然后下载无法下载PDF文档

//this is file name 
var fileName = name + "_" + DateTime.Now.ToShortDateString() + ".pdf"; 
//here I generate my pdf document 
string fullpath= GeneratePDF(); 

bool existFile= File.Exists(fullpath); 
//here I check if this document exists 
    if (existFile) 
    { 
     HttpContext.Current.Response.ContentType = "Application/pdf"; 
     HttpContext.Current.Response.AppendHeader("Content-Disposition", 
             "attachment; filename=" + fileName); 
     HttpContext.Current.Response.TransmitFile(fullpath); 
     HttpContext.Current.Response.Flush(); 
     HttpContext.Current.Response.End(); 
    } 

通过所有鳕鱼去后,成功创建文档,但下载不起作用

+4

'不work'是没有问题的说明中提出了互联网上的问题,当一个软件开发者应该给论坛。这是标准用户最常使用的一个问题描述,它们不理解或关心计算机的工作方式。 –

回答

2

我使用下面的代码,它是迫使不同类型的文档下载:

if (myfile.Exists) 
{ 
    //Clear the content of the response  
     try 
     { 
      Response.ClearContent(); 
     // Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header  
     Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name); 
     // Add the file size into the response header  
     Response.AddHeader("Content-Length", myfile.Length.ToString()); // Set the ContentType  
     Response.ContentType = ReturnMimeType(myfile.Extension.ToLower()); // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)  
     Response.TransmitFile(myfile.FullName); 
     Response.Flush(); 
     Response.Close(); 
     Response.End(); 
     } 
     finally 
     { 
      File.Delete(myfile.FullName); 
     } 
    } 

...

PDF文件ReturnMimeType包含以下行:

case ".pdf": return "application/pdf"; 
+0

我试过了你的代码,但无论如何下载不起作用 – Alex

+0

ReturnMimeType?你没有包含所有的代码。 –

1

试这

Response.ContentType = "application/pdf"; 
Response.AddHeader("Content-disposition", "inline"); 
Response.BinaryWrite(File.ReadAllBytes(Server.MapPath(fullpath)));