简体   繁体   English

如何使用C#从HTML网页提交的POST表单中下载PDF?

[英]How do I download a PDF from an HTML webpage-submitted POST form using C#?

I'm trying to programmatically download some PDF document with a C# windows form application. 我正在尝试使用C#Windows窗体应用程序以编程方式下载一些PDF文档。 Right now, I've got far enough to get a unique URL for each page that goes to download the PDF. 现在,我已经为下载PDF的每个页面提供了唯一的URL。

Each link is a webpage that submits a form via POST as soon as the page is loaded 每个链接都是一个网页,页面加载后立即通过POST提交表单

function window_onload() {
                Form1.submit();
            }

Then the PDF starts downloading. 然后,PDF开始下载。 I would like to stop the PDF from downloading and save it automatically to my local machine. 我想停止下载PDF并将其自动保存到本地计算机。 The reason I want to do this is because there are around 15-20 PDFs that I need to download every week. 我要这样做的原因是因为我每周需要下载大约15-20个PDF。

I would use a httpwebrequest object. 我将使用httpwebrequest对象。

depending on the size pdfs, and response time of servers you could do this asynchronously or synchronously. 根据pdf的大小以及服务器的响应时间,您可以异步或同步执行此操作。 This is the synchronous flavor using the GetResponse() method. 这是使用GetResponse()方法的同步风格。

void DoPDFDownload(string strMyUrl, string strPostData, string saveLocation)
{
    //create the request
    var wr = (HttpWebRequest)WebRequest.Create(myURL);
    wr.Method = "POST";
    wr.ContentLength = strPostData.Length;
    //Identify content type... strPostData should be url encoded per this next    
    //declaration
    wr.ContentType = "application/x-www-form-urlencoded";
    //just for good measure, set cookies if necessary for session management, etc.
    wr.CookieContainer = new CookieContainer();

    using(var sw = new StreamWriter(wr.GetRequestStream()))
    {
        sw.Write(strPostData);
    }

    var resp = wr.GetResponse();

    //feeling rather lazy at this point, but if you need further code for writing
    //response stream to a file stream, I can provide.
    //...

}

The following is a little method you could copy/paste into LINQPad to get an idea of how these classes work. 下面是一个可以复制/粘贴到LINQPad中的小方法,以了解这些类的工作原理。

void DoSpeedTestDownloadFromFCC()
{

string strMyUrl = "http://data.fcc.gov/api/speedtest/find?latitude=38.0&longitude=-77.5&format=json";
    //create the request
    var wr = (HttpWebRequest)WebRequest.Create(strMyUrl);
    wr.ContentLength = strPostData.Length;
            //Note that I changed the method for the webservice's standard.
            //No Content type on GET requests.
    wr.Method = "GET";
    //just for good measure, set cookies if necessary for session management, etc.
    wr.CookieContainer = new CookieContainer();


    var resp = wr.GetResponse();

    //...
    using(StreamReader sr = new StreamReader(resp.GetResponseStream()))
    {
                    //here you would write the file to disk using your preferred method
                    //in linq pad, this just outputs the text to the console.
        sr.ReadToEnd().Dump();
    }

}
Response.ClearContent();    
Response.ClearHeaders();    
Response.ContentType = "application/octet-stream";                            
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");    
Response.OutputStream.Write(data, 0, data.Length);    
Response.End();    

It will download file with the given filename to your local disk. 它将使用给定filename名将文件下载到本地磁盘。

 class DownloadLibrary
 {
 public static string getContentType(string Fileext)
 {
string contenttype = "";
switch (Fileext)
{
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".doc":
contenttype = "application/msword";
break;
case ".ppt":
contenttype = "application/vnd.ms-powerpoint";
break;
case ".pdf":
contenttype = "application/pdf";
break;
case ".jpg":
case ".jpeg":
contenttype = "image/jpeg";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".ico":
contenttype = "image/vnd.microsoft.icon";
break;
case ".zip":
contenttype = "application/zip";
break;
default: contenttype = "";
break;
}
return contenttype;
}

public static void downloadFile(System.Web.UI.Page pg, string filepath)
{
pg.Response.AppendHeader("content-disposition", "attachment; filename=" + new FileInfo(filepath).Name);
pg.Response.ContentType = clsGeneral.getContentType(new FileInfo(filepath).Extension);
pg.Response.WriteFile(filepath);
pg.Response.End();
}
}

References: http://dotnetacademy.blogspot.com/2010/07/code-to-download-file-on-buttton-click.html 参考: http : //dotnetacademy.blogspot.com/2010/07/code-to-download-file-on-buttton-click.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用c#从LiveLink下载文件? - How do I download a file from LiveLink using c#? 如何使用 URL 链接下载 PDF 文件到 c# 中的本地计算机 - How do I download a PDF file using a URL link to local computer in c# 我怎样才能使用c#将.doc或.pdf等文件从互联网下载到我的硬盘 - How could I download a file like .doc or .pdf from internet to my harddrive using c# 如何在 C# 中使用 Selenium 从 Chrome 下载 PDF - how can i download a PDF from Chrome using Selenium in C# 在Xamarin和Android中使用C#在网页的登录表单中发布帖子 - Make a post to a login form of a webpage using C# in Xamarin and Android 如何使用 C# 中的 Selenium chrome 驱动程序从网页打印 URL 列表以进行控制台? - How do I print a list of URLs to console from a webpage using Selenium chrome driver in C#? 如何使用C#(.NET)中的POST变量登录HTML表单? - How to login to HTML form using POST vars in C# (.NET)? 我如何在变量中显示变量 <p> 使用razor(C#)和html从POST请求中请求数据后的元素 - How do i display a variable in a <p> element after requesting the data from a POST request using razor(C#) and html 从C#代码发布html表单 - Post html form from C# code C#ASP.NET MVC:如何让浏览器从我的响应中自动下载pdf? - C# ASP.NET MVC: How do I get the browser to automatically download a pdf from my response?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM