为什么我的文件下载代码会生成损坏的 PDF?

发布于 2024-10-11 08:10:22 字数 1431 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

柒七 2024-10-18 08:10:22

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

        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
        }
    }

check this method , hope that helps

        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
        }
    }
ぇ气 2024-10-18 08:10:22

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

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

Please try the Following code sample to download .pdf file.

 Response.ContentType = "Application/pdf"; 
 Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf"); 
 Response.TransmitFile(Server.MapPath("~/Files/Test_PDF.pdf")); 
 Response.End();
带刺的爱情 2024-10-18 08:10:22

@赛义德·穆达西尔:
它只是一行:)

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

它将下载 pdf 文件。 :)

@Syed Mudhasir:
Its just a line :)

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

It will download pdf files. :)

假装不在乎 2024-10-18 08:10:22

这些解决方案都不适合我,或者都不完整。也许这篇文章是旧的,新版本的 .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();

None of these solutions worked for me, or were not complete. Maybe this post was old and newer versions of .NET made it easier? Anyway, the following small code did the job for me so nicely:

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

And here how you can call the method:

Task.Run(async () => { await DownloadFile(url, filePath); }).Wait();
与之呼应 2024-10-18 08:10:22
    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();
    }

确保添加: using System.Net;

    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();
    }

Make sure you add: using System.Net;

一张白纸 2024-10-18 08:10:22
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;
}
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;
}
从﹋此江山别 2024-10-18 08:10:22

这对我有用:

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();

This worked for me:

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文