Сохранить как приглашение "имя изображения" в универсальном handler.ashx? - PullRequest
4 голосов
/ 11 ноября 2011

Когда я отображаю изображение из папки с помощью Handler.ashx и затем пытаюсь сохранить изображение, щелкнув его правой кнопкой мыши, оно продолжает давать мне опцию «Сохранить как тип» универсального обработчика asp.net и имя обработчика в качестве имени файла ..

Bitmap target = new Bitmap(width, height);
    using (Graphics graphics = Graphics.FromImage(target)) {
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.DrawImage(photo, 0, 0, width, height);
        using (MemoryStream memoryStream = new MemoryStream()) {
            target.Save(memoryStream, ImageFormat.Png);
            OutputCacheResponse(context, File.GetLastWriteTime(photoPath));
            using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
            {
                memoryStream.WriteTo(diskCacheStream);
            }
            memoryStream.WriteTo(context.Response.OutputStream);
        }
    }

выше - обработчик и

ImageTiff.ImageUrl = "Handler.ashx?p=" + Parameter; 

это код позади.

Мне нужно сохранить его с именем изображения, а не как handler.ashx

Ответы [ 3 ]

5 голосов
/ 11 ноября 2011

Вы должны установить HTTP-заголовки ContentType и Content-Disposition перед отправкой ваших данных:

context.Response.ContentType = "image/png";
context.Response.Headers["Content-Disposition"] = "attachment; filename=yourfilename.png";
1 голос
/ 12 ноября 2011
          context.Response.ContentType = "image/pjpeg"; 
          context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + photoName  + "\"");

          OutputCacheResponse(context, File.GetLastWriteTime(photoPath));

           context.Response.Flush();


           using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
           {
               memoryStream.WriteTo(diskCacheStream);
           }
            memoryStream.WriteTo(context.Response.OutputStream);

Хороший ночной сон и ваша помощь сделали свое дело, я думаю :) Спасибо, ребята!

0 голосов
/ 12 ноября 2011

Если вы хотите, чтобы пользователь сохранил файл, вам необходимо отправить ContentType «application / octet-stream».

Вот код (в vb.net, извините), который мы используем (Я только что проверил, что это приводит к правильному имени файла для пользователя при запросе из ashx):

    With context
        Try
            ' Remove what other controls may have been put on the page
            .ClearContent()
            ' Clear any headers
            .ClearHeaders()
        Catch theException As System.Web.HttpException
            ' Ignore this exception, which could occur if there were no HTTP headers in the response
        End Try

        .ContentType = "application/octet-stream"
        .AddHeader("Content-Disposition", "attachment; filename=" & sFileNameForUser)

        .TransmitFile(sFileName)

        ' Ensure the file is properly flushed to the user
        .Flush()

        ' Ensure the response is closed
        .Close()

        Try
            .End()
        Catch
        End Try

    End With

C # перевод:

try
{
        // Remove what other controls may have been put on the page
    context.ClearContent();
        // Clear any headers
    context.ClearHeaders();
}
catch (System.Web.HttpException theException)
{
        // Ignore this exception, which could occur if there were no HTTP headers in the response
}

context.ContentType = "application/octet-stream";
context.AddHeader("Content-Disposition", "attachment; filename=" + sFileNameForUser);

context.TransmitFile(sFileName);

    // Ensure the file is properly flushed to the user
context.Flush();

    // Ensure the response is closed
context.Close();

try
{
    context.End();
}
catch
{
}
...