Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show stored pdf btye array in SQL Server to asp.net WebForm in a image box?

i am developing a web application in that i need to store image files and some other documents in a database and then i have to show them on a web page in an image box preferably. i have stored images in database and also PDF files in the form of byte array and i used a Generic Handler to get byte array from database and then show them in a image box it works fine for the images but it does not work with PDF files.

public class ShowImage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    { 
        Int32 imgID;
        if (context.Request.QueryString["id"] != null)
            imgID = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        byte[] buffer = ShowEmpImage(imgID);
        context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)
    {
        dbClass db = new dbClass();
        string sql = "SELECT imgfile FROM myFiles WHERE id = @ID";
        SqlCommand cmd = new SqlCommand(sql, db.con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        object img = null;
        try
        {
            db.Connect();
            img = cmd.ExecuteScalar();
        }
        catch
        {
            return null;
        }
        finally
        {
            db.Disconnect();
        }
        return new MemoryStream((byte[])img);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

please guide me how can i show PDF files and some other files to the image box? actually the problem is my application runs with the existing application and that have no way to store extensions of files so the only way i can show files is "show them in as a image" but if their is a better way then help me out friends.

like image 436
Aqeel Avatar asked Oct 09 '22 12:10

Aqeel


1 Answers

There's a reason that PDF doesn't work when representing it as an image... it isn't an image. Additionally, claiming it is "image/jpeg" is going to make it pretty broken unless the browser does explicit file-header checking, and really need fixing IMO. If you don't currently store the file name / extension / MIME / something then frankly: that's a problem you need to fix.

For displaying a PDF, I suspect you'd need to use an <iframe> rather than an <img>, which a: might not work on all browsers, and b: might not be very convenient to the caller. Personally I'd just offer a download link (and in the handler, use content-disposition to tell the browser to treat it as a download).

like image 175
Marc Gravell Avatar answered Oct 13 '22 11:10

Marc Gravell