Я хочу, чтобы браузер загрузил PDF-документ с сервера, а не открывал файл в самом браузере. Я использую С#.
Ниже приведен пример кода, который я использовал. Он не работает.
string filename = "Sample server url";
response.redirect(filename);
Я хочу, чтобы браузер загрузил PDF-документ с сервера, а не открывал файл в самом браузере. Я использую С#.
Ниже приведен пример кода, который я использовал. Он не работает.
string filename = "Sample server url";
response.redirect(filename);
Вы должны посмотреть заголовок Content-Disposition; например, установка "Content-Disposition" на "attachment; filename = foo.pdf" подскажет пользователю (обычно) диалоговое окно "Сохранить как: foo.pdf", а не открывает его. Это, однако, должно исходить от запроса, который выполняет загрузку, поэтому вы не можете сделать это во время перенаправления. Однако для этой цели ASP.NET предлагает Response.TransmitFile
. Например (если вы не используете MVC, у которого есть другие предпочтительные параметры):
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
Response.TransmitFile(filePath);
Response.End();
Если вы хотите отобразить файл (ы), чтобы вы могли сохранить их в конце, а не открывать в браузере, вы можете попробовать следующий фрагмент кода:
//create new MemoryStream object and add PDF file’s content to outStream.
MemoryStream outStream = new MemoryStream();
//specify the duration of time before a page cached on a browser expires
Response.Expires = 0;
//specify the property to buffer the output page
Response.Buffer = true;
//erase any buffered HTML output
Response.ClearContent();
//add a new HTML header and value to the Response sent to the client
Response.AddHeader("content-disposition", "inline; filename=" + "output.pdf");
//specify the HTTP content type for Response as Pdf
Response.ContentType = "application/pdf";
//write specified information of current HTTP output to Byte array
Response.BinaryWrite(outStream.ToArray());
//close the output stream
outStream.Close();
//end the processing of the current page to ensure that no other HTML content is sent
Response.End();
Однако, если вы хотите загрузить файл с помощью клиентского приложения, вам придется использовать класс WebClient.
Я использую это, установив параметр inline в true, который будет отображаться в браузере false. Он отобразит сохранение в диалоговом окне в браузере.
public void ExportReport(XtraReport report, string fileName, string fileType, bool inline)
{
MemoryStream stream = new MemoryStream();
Response.Clear();
if (fileType == "xls")
report.ExportToXls(stream);
if (fileType == "pdf")
report.ExportToPdf(stream);
if (fileType == "rtf")
report.ExportToRtf(stream);
if (fileType == "csv")
report.ExportToCsv(stream);
Response.ContentType = "application/" + fileType;
Response.AddHeader("Accept-Header", stream.Length.ToString());
Response.AddHeader("Content-Disposition", String.Format("{0}; filename={1}.{2}", (inline ? "Inline" : "Attachment"), fileName, fileType));
Response.AddHeader("Content-Length", stream.Length.ToString());
//Response.ContentEncoding = System.Text.Encoding.Default;
Response.BinaryWrite(stream.ToArray());
Response.End();
}
Они почти одинаковы в большинстве случаев, но есть разница:
Добавить заголовок заменит предыдущую запись тем же ключом
Append header не заменит ключ, скорее добавит еще один.