读书人

存放图片路径到ACCESS数据库并读取显示

发布时间: 2012-02-04 15:43:09 作者: rapoo

存放图片路径到ACCESS数据库并读取显示
RT, 本人初学ASP.NET,想做一个这样的例子。希望网友给我实现这个功能的重要的步骤或者完整的一个代码例子!(就是如何保存图片路径到ACCESS数据库,又如何读取出来显示)

[解决办法]
这里用的是Mysql数据库 数据字段是Blob,如果是ACCESS就用“OLE 对象”字段,sql是IMAGE字段
还有 你把MySqlConnection该成OleDBConnection(ACCESS)或SqlConnection(SQL数据库)
依次类推,把 MySqlCommand 改成OleDBCommand 等等 ....知道了吧

C# code
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.IO; using System.Drawing.Imaging; using MySql.Data.MySqlClient;//引用MYSQL命名空间 public partial class _Default : System.Web.UI.Page {       MySqlConnection conn = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conmy"]);     protected void Page_Load(object sender, EventArgs e)     {         if (!this.Page.IsPostBack)         {             this.show();         }     }          protected void Button1_Click(object sender, EventArgs e)     {         if (FileUpload1.HasFile)         {             //文件扩展名             string Ex=FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf('.') + 1);             if (Ex.ToLower() == "jpg" || Ex.ToLower() == "gif")             {                 int ImageSize = FileUpload1.PostedFile.ContentLength;//图片的大小                 string ImageType = this.FileUpload1.PostedFile.ContentType;//图片类型                 Stream ImageStream = this.FileUpload1.PostedFile.InputStream;                 Byte[] ImageCount = new Byte[ImageSize];//调用方法转化二进制数据                 int bt = ImageStream.Read(ImageCount, 0, ImageSize);                            MySqlCommand comm = new MySqlCommand("testpic",conn);                 comm.CommandType = CommandType.StoredProcedure;                 MySqlParameter pj = new MySqlParameter("?myimage", MySqlDbType.LongBlob,ImageCount.Length);//图片                 pj.Value =ImageCount;//给这字段赋值二进制数据                 comm.Parameters.Add(pj);                 MySqlParameter pname = new MySqlParameter("?imagename", MySqlDbType.VarChar, 100);//图片名称                 pname.Value=FileUpload1.FileName;                 comm.Parameters.Add(pname);                 MySqlParameter psize = new MySqlParameter("?imagesize", MySqlDbType.Int32);//图片名称                 psize.Value =ImageSize;                 comm.Parameters.Add(psize);                 conn.Open();                 comm.ExecuteNonQuery();                 conn.Close();                      this.Label1.Text="插入成功!";               this.show();                                    }             else             {                 this.Label1.Text = "格式不正确!!!";             }             }         else         {             this.Label1.Text = "没有文件!!!";         }     }     private byte[] ImageToByte(string path)//声名一个把图片转化到二进制数据的方法     {         FileStream buffer = new FileStream(path, FileMode.Open, FileAccess.Read);         BinaryReader br = new BinaryReader(buffer);         byte[] image = br.ReadBytes((int)buffer.Length);         return image;     }     private void show()     {         MySqlDataAdapter da = new MySqlDataAdapter("select * from imgpic", conn);         DataSet ds = new DataSet();         da.Fill(ds, "a");         this.GridView1.DataSource = ds.Tables["a"].DefaultView;         this.GridView1.DataKeyNames = new string[] { "id" };         this.GridView1.DataBind();     }       protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)     {         string sid = this.GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();         Session["id"] = sid;         this.Label1.Text = sid;         this.Image1.ImageUrl = "jpg2.aspx";     } } 读取图片 using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Drawing; using System.Drawing.Imaging; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Data.SqlClient; using MySql.Data.MySqlClient; public partial class Default2 : System.Web.UI.Page {     MySqlConnection conn = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["conmy"]);     protected void Page_Load(object sender, EventArgs e)     {                if (!this.Page.IsPostBack)         {             this.show();           }     }     public void show()     {                      string ss = Request.QueryString["id"].ToString();             string s3 = "select * from imgpic  where id=" + ss;             MySqlCommand comm = new MySqlCommand(s3, conn);             conn.Open();             MySqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection);             while(dr.Read())             {                 Response.Clear();                 Response.C;                 Response.BinaryWrite((byte[])dr["myimg"]);//读取             }             Response.End();             conn.Close();     } } 注意图片显示要在另一张页面中 在你要显示的页面添加img 控件src="显示你图片的页面"; 


[解决办法]
本机路径存入数据库:XIANCE/2007712123645.jpg(建立虚拟目录,上载图片,路径写入数据库)
外网路径存入数据库:http://www.nongli.com/images/logo.gif(图片网址直接存入)
然后绑定图片控件显示。
外网:
<tr>
<td class="style9" colspan="4" valign="top">
<asp:DataList ID="DataList6" runat="server" CellPadding="4" ForeColor="#333333"
Width="100%" RepeatDirection="Horizontal" RepeatColumns="4"
style="text-align: center">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingItemStyle BackColor="White" />
<ItemStyle BackColor="#EFF3FB" />
<SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderTemplate>
慈善点击(日行一善  举手之劳)
</HeaderTemplate>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<ItemTemplate>
<asp:HyperLink ID="HyperLink4" runat="server"
ImageUrl='<%# DataBinder.Eval(Container.DataItem, "TuShi")%>'
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "wanzhi")%>'
Target="_blank"
ToolTip='<%# DataBinder.Eval(Container.DataItem, "jie")%>' Width="99%"><%# DataBinder.Eval(Container.DataItem, "mingcheng")%></asp:HyperLink>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
--------------------------------------------
DataSet CiShan = Socut.Data.ExecuteDataSet("SELECT TOP 16 * FROM Youqinglianjie WHERE leixin='" + "慈善" + "' order by ID asc");
DataList6.DataSource = CiShan;
DataList6.DataBind();
--------------------------------------------------上载文件方法自己找,以下略为提示
string path = Server.MapPath("~/XIANCE/");//虚拟目录


if (ine <= 0) { ine = TpMingCheng.IndexOf(".jpg"); }
if (ine <= 0) { ine = TpMingCheng.IndexOf(".bmp"); }
if (ine <= 0) { ine = TpMingCheng.IndexOf(".gif"); }
if (ine <= 0) { ine = TpMingCheng.IndexOf(".png"); }

if (ine > 0)
{
FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
}
else
{ Label8.Text = "文件不符合格式或大于2Mb?"; }

}
catch (Exception error)
{ Response.Write("上载相片失败,原因:" + error.Message); }

读书人网 >asp.net

热点推荐