今天遇到一个企业网站的项目,客户要求系统里面的产品数据表要用他们公司的ERP里面的数据库,里面的产品图片还可以更换(他的ERP的产品图片是存放到IMAGE字段里面的),如果没有可更换的图片,那么就直接读取产品表的ERP插入的原图,找了很多时候,才找到个可行读取IMAGE字段并把图片显示在浏览器的代码:
c# 代码
-
try
- {
-
byte[] imgData;
-
imgData = (byte[])dtbl_pd.Rows[0]["yytp"];
-
int iLength = imgData.Length;
-
-
-
- Response.OutputStream.Write(imgData, 0, iLength);
- }
-
catch (Exception ex)
- {
-
-
}
调用很简单,比如上面的代码所在的页面名为:Img.aspx,那么可以在需要的页面里面插入:
<img src="Img.aspx" />
另外有了读取顺便也提供个插入吧,经过测试为可行的
InsertImage.aspx关键代码:
HTML代码
-
<form enctype="multipart/form-data" runat="server" id="Form1">
-
<table runat="server" width="700" align="left" id="Table1" cellpadding="0" cellspacing="0" border="0">
-
<tbody>
-
<tr>
-
<td>上传图片(选择你要上传的图片)</td>
-
<td>
-
<input type="file" id="UP_FILE" runat="server" style="Width:320" accept="text/*" name="UP_FILE" />
-
</td>
-
</tr>
-
<tr>
-
<td>文件说明(添加上传图片说明,如:作者、出处) </td>
-
<td>
-
<asp:TextBox RUNAT="server" WIDTH="239" ID="txtDescription" />
-
</td>
-
</tr>
-
<tr>
-
<td>
-
<asp:Label RUNAT="server" ID="txtMessage" FORECOLOR="red" />
-
</td>
-
<td>
-
<asp:Button ID="Button1" RUNAT="server" WIDTH="239" onCLICK="Button_Submit" TEXT="UploadImage" /></td>
-
</tr>
-
</tbody>
-
</table>
-
</form>
InsertImage.aspx.cs关键代码:
c# 代码
-
protected void Button_Submit(System.Object sender, System.EventArgs e)
- {
-
HttpPostedFile UpFile = UP_FILE.PostedFile;
-
FileLength = UpFile.ContentLength;
-
try
- {
-
if (FileLength == 0)
-
{
-
txtMessage.Text = "<b>请你选择你要上传的文件</b>";
- }
-
else
- {
-
Byte[] FileByteArray = new Byte[FileLength];
-
Stream StreamObject = UpFile.InputStream;
-
- StreamObject.Read(FileByteArray, 0, FileLength);
-
-
SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=CompanyWebSiteData;User ID=sa;Pwd=chenfeng;");
-
String SqlCmd = "Insert INTO cp (cpbh,yytp) valueS (@cpbh,@Image)";
-
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
-
CmdObj.Parameters.Add("@Image", SqlDbType.Binary, FileLength).Value = FileByteArray;
-
CmdObj.Parameters.Add("@cpbh", SqlDbType.VarChar, 200).Value = txtDescription.Text;
-
-
-
-
- Con.Open();
- CmdObj.ExecuteNonQuery();
- Con.Close();
-
txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";
- }
- }
-
catch (Exception ex)
- {
- txtMessage.Text = ex.Message.ToString();
- }
-
}
|
请发表评论