图片已经放进数据库里了,字段名称是是image,类型是image
上传 图片使用了fileupload控件,上传成功之后,我想读出来
protected void 上传按钮_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string fileextension = FileUpload1.PostedFile.ContentType;
if(fileextension=="image/jpeg" ¦ ¦ fileextension=="image/bmp")
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constr"].ToString());
Stream imgs=FileUpload1.PostedFile.InputStream;
int imglen = FileUpload1.PostedFile.ContentLength;
byte[] imgdata=new byte[imglen];
int i = imgs.Read(imgdata,0,imglen);
string sqlstr = "insert into gg (imgtype,image) values (@imagetype,@image)";
con.Open();
SqlCommand com = new SqlCommand(sqlstr,con);
com.Parameters.Add(new SqlParameter("@imagetype", SqlDbType.VarChar, 1000));
com.Parameters.Add(new SqlParameter("@image", SqlDbType.Image, 16));
com.Parameters["@imagetype"].Value = fileextension;
com.Parameters["@image"].Value = imgdata;
if ((int)com.ExecuteNonQuery() > 0)
{
Response.Write(" ");
}
else
{
}
con.Close();
}
else
{
}
}
上传成功之后,我想读出来,新建一个页面show.aspx用来读取
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
public partial class show : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.Params["id"] != null)
{
this.hly(Request.Params["id"].ToString().Trim());
}
}
}
private void hly(string id)
{
string sql = " select * from gg WHERE image is not null and id='" + id + "'";
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constr"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand(sql,con);
cmd.CommandText = sql;
//SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
//Response.ContentType = "image/jpeg";
//Response.ContentType = "application/x-msdownload ; Charset=utf-8";
//Response.ContentType = "application/octet-stream";
Response.ContentType = "image/jpg";
Response.BinaryWrite((byte[])dr["image"]);//直接写二进制流到页面
Response.End();
}
}
}
}