【问题标题】:Why does my code to download files produce corrupted PDFs? [closed]为什么我下载文件的代码会生成损坏的 PDF? [关闭]
【发布时间】:2011-06-06 09:09:48
【问题描述】:

使用以下代码下载 PDF 文件时遇到问题:

WebClient client = new WebClient();
client.DownloadFile(remoteFilename, localFilename);

虽然其他文件已成功下载,但当我下载并保存 PDF 文档时,当我尝试打开它时显示文档已修复错误。

【问题讨论】:

  • 有什么问题?
  • 我的问题是在下载 pdf 文件并通过上述代码将其保存为 pdf 文档后。当我尝试打开它时显示文档已修复错误。
  • 我希望下面的链接能帮助你...stackoverflow.com/questions/10829168/…
  • 我不认为这个问题是可以回答的,因为提供的信息太少了。通过使用WebClient 和术语“download(ing)”,很明显这是关于 client 端代码,那么为什么有这么多答案显示 server 端代码(并且也得到了赞成)?误会在哪里?

标签: c# .net pdf webclient webclient-download


【解决方案1】:

检查这个方法,希望对你有帮助

        public static void DownloadFile(HttpResponse response,string fileRelativePath)
    {
        try
        {
            string contentType = "";
            //Get the physical path to the file.
            string FilePath = HttpContext.Current.Server.MapPath(fileRelativePath);

            string fileExt = Path.GetExtension(fileRelativePath).Split('.')[1].ToLower();

            if (fileExt == "pdf")
            {
                //Set the appropriate ContentType.
                contentType = "Application/pdf";
            }

            //Set the appropriate ContentType.
            response.ContentType = contentType;
            response.AppendHeader("content-disposition", "attachment; filename=" + (new FileInfo(fileRelativePath)).Name);

            //Write the file directly to the HTTP content output stream.
            response.WriteFile(FilePath);
            response.End();
        }
        catch
        {
           //To Do
        }
    }

【讨论】:

  • 你必须设置 contentType = "Application/pdf";确保下载的文件是正确的PDF文件
  • 谢谢 Mahmoud 我试过了,但出现以下错误:找不到类型或命名空间名称“HttpResponse”(您是否缺少 using 指令或程序集引用?)
  • @Syed Mudhasir。您应该在您的参考项目中添加参考“System.Web”
  • 我确实添加了那行“使用 Systems.Web;”但我得到同样的错误
  • @Mahmoud:网络应用程序
【解决方案2】:

@Syed Mudhasir: 它只是一条线:)

client.DownloadFileAsync(new Uri(remoteFilename, UriKind.Absolute), localFilename);

它将下载pdf文件。 :)

【讨论】:

    【解决方案3】:

    请尝试以下代码示例以下载 .pdf 文件。

     Response.ContentType = "Application/pdf"; 
     Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf"); 
     Response.TransmitFile(Server.MapPath("~/Files/Test_PDF.pdf")); 
     Response.End();
    

    【讨论】:

    • 这是服务器端代码,而问题是询问WebClient 的使用,它是客户端。这也与一年多前的@MahmoudFarahat's answer 基本相同。
    【解决方案4】:

    这对我有用:

    string strURL = @"http://192.168.1.xxx/" + sDocumento;
    WebClient req = new WebClient();
    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.ClearContent();
    response.ClearHeaders();
    response.Buffer = true;
    response.AddHeader("Content-Disposition", "attachment;filename=\"" + sDocumento + "\"");
    byte[] data = req.DownloadData(strURL);
    response.BinaryWrite(data);
    response.End();
    

    【讨论】:

    • 如果您删除对System.Web 命名空间的引用,该名称未在问题中指定并暗示这是服务器端代码,这将变为简单的WebClient req = new WebClient(); byte[] data = req.DownloadData(strURL);,这与问题是什么。那么这如何解决问题呢?
    【解决方案5】:

    这些解决方案都不适合我,或者不完整。也许这篇文章是旧的,新版本的 .NET 使它更容易?无论如何,下面的小代码很好地为我完成了这项工作:

      static async Task DownloadFile(string url, string filePath)
      {
         using (var wc = new WebClient())
            await wc.DownloadFileTaskAsync(url, filePath);
      }
    

    以及如何调用该方法:

    Task.Run(async () => { await DownloadFile(url, filePath); }).Wait();
    

    【讨论】:

      【解决方案6】:
          public void DownloadPdf(String downloadLink, String storageLink)
          {
              using (WebClient wc = new WebClient())
              {
                  wc.DownloadFile(downloadLink, storageLink);
              }
              Console.Write("Done!");
          }
      
          static void Main(string[] args)
          {
              Program test = new Program();
              test.DownloadPdf("*PDF file url here*", @"*save location here/filename.pdf*");
              Console.ReadLine();
          }
      

      确保添加:使用 System.Net;

      【讨论】:

      • 这基本上与问题中的代码相同,只是包装在一个方法中。当问题中的代码没有生成可读文件时,为什么期望这段代码生成可读文件?
      【解决方案7】:
      public void DownloadTeamPhoto(string fileName)
      {
        string mimeType = MimeAssistance.GetMimeFromRegistry(fileName);
        Response.ContentType = mimeType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + 
        Path.GetFileName(basePath + fileName)); //basePath= @"~/Content/
        Response.WriteFile(basePath + fileName); //basePath= @"~/Content/
        Response.End();
      
      }
      
      public static string GetMimeFromRegistry(string Filename)
      {
        string mime = "application/octetstream";
        string ext = System.IO.Path.GetExtension(Filename).ToLower();
        Microsoft.Win32.RegistryKey rk = 
        Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
      
        if (rk != null && rk.GetValue("Content Type") != null)
           mime = rk.GetValue("Content Type").ToString();
      
        return mime;
      }
      

      【讨论】:

      • 这甚至在做什么以及它如何应用于问题?它似乎正在弄清楚 MIME 类型,那么这应该在服务器端运行吗?您如何知道服务器正在运行 Windows 并在下载方的控制下? WebClient 和文件传输在哪里?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2021-05-20
      • 2019-08-19
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 2010-10-31
      相关资源
      最近更新 更多