Search code examples
c#asp.netcontent-typeashx

ASHX Image Download Saved as ASHX


When a user clicks my link it brings up the save as dialog, but it wants to save it as a ashx file in any other browser than IE. The file is standard jpeg that is being taken from a database. What would cause this to do?

       string id = ctx.Request.QueryString["id"];

        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand("EBig", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@EID", id);

        byte[] pict = null;
        ctx.Response.ContentType = "image/pjpeg";
        try
        {
            con.Open();
            pict = (byte[])cmd.ExecuteScalar();

            ctx.Response.Clear();

            ctx.Response.AppendHeader("content-disposition", "attachment;");
            ctx.Response.ContentType = "image/pjpeg";
            ctx.Response.BinaryWrite(pict);
            ctx.Response.Flush();
            ctx.Response.End();
        }
        catch
        {

        }
        finally
        {
            con.Close();
        }

Solution

  • Hanselman has a post on this. It involves setting an additional attribute named filename on your Content-Disposition response header.

    The related RFC is here, relevant section is 2.3:

    The sender may want to suggest a filename to be used if the entity is detached and stored in a separate file. If the receiving MUA writes the entity to a file, the suggested filename should be used as a basis for the actual filename, where possible.