【问题标题】:Download a PDF from a third party using ASP.NET HttpWebRequest/HttpWebResponse使用 ASP.NET HttpWebRequest/HttpWebResponse 从第三方下载 PDF
【发布时间】:2014-12-12 03:51:00
【问题描述】:

我想发送一个 url 作为查询字符串,例如

localhost/abc.aspx?url=http:/ /www.site.com/report.pdf

并检测上述 URL 是否返回 PDF 文件。如果它会返回 PDF,那么它会自动保存,否则会出错。

有些页面使用 Handler 来获取文件,所以在这种情况下,我也想检测和下载相同的文件。

localhost/abc.aspx?url=http:/ /www.site.com/page.aspx?fileId=223344

上面可能会返回一个pdf文件。

捕捉这个的最佳方法是什么?

谢谢

【问题讨论】:

    标签: c# asp.net httpwebrequest httpwebresponse


    【解决方案1】:

    您可以像这样下载 PDF

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = req.GetResponse();
    //check the filetype returned
    string contentType = response.ContentType;
    if(contentType!=null)
    {
        splitString = contentType.Split(';');
        fileType = splitString[0];  
    }
    
    //see if its PDF
    if(fileType!=null && fileType=="application/pdf"){
        Stream stream = response.GetResponseStream();
        //save it
        using(FileStream fileStream = File.Create(fileFullPath)){
          // Initialize the bytes array with the stream length and then fill it with data
          byte[] bytesInStream = new byte[stream.Length];
          stream.Read(bytesInStream, 0, bytesInStream.Length);    
          // Use write method to write to the file specified above
          fileStream.Write(bytesInStream, 0, bytesInStream.Length);
        }
    }
    
    response.Close();
    

    它可能来自 .aspx 处理程序这一事实实际上并不重要,它是使用的服务器响应中返回的 mime。

    如果您获得的是通用 mime 类型,例如 application/octet-stream,那么您必须使用更具启发性的方法。

    假设您不能简单地使用文件扩展名(例如.aspx),那么您可以先将文件复制到 MemoryStream(请参阅How to get a MemoryStream from a Stream in .NET?)。一旦你有了文件的内存流,你就可以“厚颜无耻”地偷看它(我说厚脸皮是因为它不是解析 PDF 文件的正确方法)

    我不是 PDF 格式方面的专家,但我相信使用 ASCII 阅读器读取前 5 个字符会产生“%PDF-”,因此您可以使用

    bool isPDF;
    using(  StreamReader srAsciiFromStream = new StreamReader(memoryStream,
        System.Text.Encoding.ASCII)){
            isPDF = srAsciiFromStream.ReadLine().StartsWith("%PDF-");
    
    }
    
    //set the memory stream back to the start so you can save the file
    memoryStream.Position = 0;
    

    【讨论】:

    • 一些 url 返回 mime 类型的 application/octet-stream 可能有任何类型的文件。在这种情况下,我们如何检测 pdf?
    • 我们如何使用 Response.Write() 将其作为 Content Typr="application/pdf" 写入客户端的浏览器?
    • 你能告诉我从哪里我可以阅读更多关于流的资源。
    • Response.ContentType = "application/pdf";
    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多