在asp.net中从数据库中检索图像

时间:2014-07-06 11:56:54

标签: asp.net

我正在从数据库上传和检索图像。图像被上传到数据库中但在同一页面上检索时出现问题。它没有显示图像。它给出了一个异常"无法转换类型' System.Byte []&#的对象39;输入' System.String'。"在handler.ashx中的行字符串s =(String)img;

protected void Button1_Click(object sender, EventArgs e)
    {
        {
            SqlConnection connection = null;

     try{   

            FileUpload img = (FileUpload)FileUpload1;
            Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = FileUpload1.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
            //  string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
            connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");

            connection.Open();
            string sql = "INSERT INTO Table1(ImageName,Image) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", TextBox1.Text.Trim());
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            Label1.Text = String.Format("Employee ID is {0}", id);

        Image1.ImageUrl = "~/Handler.ashx?id=" + id;
    }
        catch (Exception)
        {    //error        }
            Label1.Text = "ERROR";
        }
    }
}

处理程序 ................

public void ProcessRequest (HttpContext context) {

    Int32 empno;
    if (context.Request.QueryString["id"] != null)
        empno = Convert.ToInt32(context.Request.QueryString["id"]);
    else
        throw new ArgumentException("No parameter specified");

    context.Response.ContentType = "image/jpeg";
    Stream strm = ShowEmpImage(empno);
    byte[] buffer = new byte[4096];
    int byteSeq = strm.Read(buffer, 0, 4096);

    while (byteSeq > 0)
    {
        context.Response.OutputStream.Write(buffer, 0, byteSeq);
        byteSeq = strm.Read(buffer, 0, 4096);
    }    
}


public Stream ShowEmpImage(int empno)
{

    SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
    string sql = "SELECT Image FROM Table1 WHERE ImageID = @ID";
    SqlCommand cmd = new SqlCommand(sql, connection);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@ID", empno);
    connection.Open();
    object img = cmd.ExecuteScalar();
    String s = (String)img;
    byte[] data = System.Text.Encoding.ASCII.GetBytes(s);
  return new MemoryStream(data);




     //   return null;



     //   connection.Close();

}



public bool IsReusable {
    get {
        return false;
    }
}

} .................. 数据库 ................ 表1包含

ImageID------int
ImageName----varchar(50)
Image--------Image

0 个答案:

没有答案