#asp.net
#asp.net
Вопрос:
я загружаю и извлекаю изображение из базы данных. изображение загружено в базу данных, но при его извлечении на том же page.it не показывает image.it выдает исключение «Не удается привести объект типа ‘System.Байт[]’для ввода’системы.Строка’.» в обработчике.ashx в строке String s = (Строка)img;
protected void Button1_Click(object sender, EventArgs e)
{
{
SqlConnection connection = null;
try{
FileUpload img = (FileUpload)FileUpload1;
Byte[] imgByte = null;
if (img.HasFile amp;amp; 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
Комментарии:
1. Существуют ли данные в SQL Server и вы убедились, что ваш запрос select действительно извлекает данные?
2. что ж, теперь оно показывает исключение «Не удается привести объект типа ‘System. Байт[]’для ввода’системы. Строка'» в строке s=(String)img; спасибо.