简体   繁体   中英

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. Right now, I've got far enough to get a unique URL for each page that goes to download the PDF.

Each link is a webpage that submits a form via POST as soon as the page is loaded

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

Then the PDF starts downloading. I would like to stop the PDF from downloading and save it automatically to my local machine. The reason I want to do this is because there are around 15-20 PDFs that I need to download every week.

I would use a httpwebrequest object.

depending on the size pdfs, and response time of servers you could do this asynchronously or synchronously. This is the synchronous flavor using the GetResponse() method.

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.

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.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM