Потоковая передача файлов в ASP.NET работает в Firefox, но не в Internet Explorer - PullRequest
1 голос
/ 31 июля 2009

Я динамически генерирую Zip-файл на странице ASP.NET и затем отправляю поток в Response.

В Firefox я могу загрузить файл с именем Images.zip. Работает правильно. В Internet Explorer 7 он пытается загрузить файл с именем ZipExport.aspx или, если он находится в универсальном обработчике, ZipExport.ashx и сообщает, что его невозможно найти на сервере, и он не работает.

Вот мой код:

Response.BufferOutput = true;
Response.ClearHeaders();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment; filename=Images.zip");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoServerCaching();
Response.Cache.SetNoStore();
Response.Cache.SetMaxAge(System.TimeSpan.Zero);
ZipFile zip = new ZipFile();
zip.AddFile(Server.MapPath("sample1.png"));
zip.Save(Response.OutputStream);

Я не хочу создавать HTTPHandler для определенного файла и регистрировать его в IIS.

Есть что-то простое, что я упускаю или Internet Explorer виноват в том, что проигнорировал мой заголовок размещения контента?

Редактировать: я удалил эти строки и все заработало:

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

Редактировать: Вот рабочий код, если кому-то интересно:

public void ProcessRequest(HttpContext context)
{  
    context.Response.Clear();
    context.Response.BufferOutput = false;
    context.Response.ContentType = "application/octet-stream";
    context.Response.AddHeader("content-disposition", 
        "attachment; filename=ChartImages.zip");
    context.Response.Cache.SetNoServerCaching();
    context.Response.Cache.SetMaxAge(System.TimeSpan.Zero);
    using(ZipFile zip = new ZipFile())
    {
        zip.AddFile(context.Server.MapPath("sample1.png"));
        zip.Save(context.Response.OutputStream);
    }
    context.ApplicationInstance.CompleteRequest();
}

Ответы [ 6 ]

3 голосов
/ 31 июля 2009

Заменить Response.End на HttpContext.Current.ApplicationInstance.CompleteRequest

Попробуйте эту урезанную версию:

Response.Clear();
Response.BufferOutput = false;

Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=Images.zip");
using(ZipFile zip = new ZipFile())
{
  zip.AddFile(Server.MapPath("sample1.png"));
  zip.Save(Response.OutputStream);
}
HttpContext.Current.ApplicationInstance.CompleteRequest();

Если не использовать Microsoft Fiddler, чтобы увидеть, что еще может не получаться

3 голосов
/ 31 июля 2009

Вы должны создать ASHX Handler для этого. Вы пытались использовать тип контента «application / zip» вместо этого?

2 голосов
/ 31 июля 2009

Вместо Response.ClearHeaders () выполните полное Response.Clear () , а затем выполните Response.End ()

1 голос
/ 02 сентября 2009

Я только что столкнулся с той же проблемой (и исправить) спасибо.

Один момент, который может помочь будущим поисковикам, заключается в том, что проблема возникла только у меня на сайтах HTTPS. Код работал нормально на моем локальном HTTP-сервере.

Я предполагаю, что с HTTPS он все равно не будет кэширован, поэтому может быть заключен в условие "if (Request.IsSecureConnection)".

0 голосов
/ 08 мая 2017

Я только что столкнулся с той же проблемой, и мне удалось исправить

Response.Clear (); Response.BufferOutput = false;

                    Response.ContentType = "application/zip";
                    //Response.AddHeader("content-disposition", "inline; filename=\"" + ArchiveName + "\"");
                    Response.AddHeader("content-disposition", "attachment; filename=\"" + ArchiveName + "\"");
                    zipFile.Save(Response.OutputStream);
                   // Response.Close();
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    Response.Clear();
                    Response.End();
0 голосов
/ 31 июля 2009

Я никогда не использовал класс ZipFile, при этом при отправке файлов я использую Response.BinaryWrite ()

//Adds document content type
context.Response.ContentType = currentDocument.MimeType;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.AddHeader("content-disposition", "attachment;filename=\"" + currentDocument.Name + "\"");



//currentDocument.Document is the byte[] of the file
context.Response.BinaryWrite(currentDocument.Document);

context.Response.End();
...