Потоковая передача файла в ASP.NET работает в Firefox, но не в Internet Explorer

StackOverflow https://stackoverflow.com/questions/1209002

Вопрос

Я динамически генерирую 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 в игнорировании моего заголовка content-disposition?

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

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();
}
Это было полезно?

Решение

Замените 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, чтобы увидеть, что еще может пойти не так.

Другие советы

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

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

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

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

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

Я никогда не использовал класс 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();

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

Ответ.Очистить ();Ответ.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();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top