Как загрузить PDF из формы POST, отправленной с веб-страницы HTML, с помощью C #? - PullRequest
0 голосов
/ 07 октября 2010

Я пытаюсь программным способом загрузить какой-нибудь PDF-документ с помощью приложения для формы C # windows.Прямо сейчас у меня есть достаточно далеко, чтобы получить уникальный URL для каждой страницы, которая идет для загрузки PDF.

Каждая ссылка - это веб-страница, которая отправляет форму через POST, как только страница загружена

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

Затем начинается загрузка PDF.Я хочу остановить загрузку PDF и автоматически сохранить его на моем локальном компьютере.Я хочу сделать это потому, что мне нужно каждую неделю загружать около 15-20 PDF-файлов.

Ответы [ 3 ]

1 голос
/ 07 октября 2010

Я бы использовал httpwebrequest объект.

в зависимости от размера pdfs и времени отклика серверов, вы можете сделать это асинхронно или синхронно.Это синхронный вариант с использованием метода 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.
    //...

}

Ниже приведен небольшой метод, который можно скопировать / вставить в 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();
    }

}
0 голосов
/ 07 августа 2012
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();    

Будет загружен файл с указанным filename на ваш локальный диск.

0 голосов
/ 02 ноября 2010
 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();
}
}

Рекомендации: http://dotnetacademy.blogspot.com/2010/07/code-to-download-file-on-buttton-click.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...