c# 代码
- try
- {
- byte[] imgData;
- imgData = (byte[])dtbl_pd.Rows[0]["yytp"];//图片IMAGE字段
- int iLength = imgData.Length;
- // FileStream fs = new FileStream("E:\\Project\\CompanyWebSite\\1.gif", System.IO.FileMode.Create, System.IO.FileAccess.Write);//可用于生成实际的文件
- // fs.Write(imgData, 0, iLength);
- //fs.Close();
- 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; //HttpPostedFile对象,用于读取图象文件属性
- FileLength = UpFile.ContentLength; //记录文件长度
- try
- {
- if (FileLength == 0)
- { //文件长度为零时
- txtMessage.Text = "<b>请你选择你要上传的文件</b>";
- }
- else
- {
- Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
- Stream StreamObject = UpFile.InputStream; //建立数据流对像
- //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
- StreamObject.Read(FileByteArray, 0, FileLength);
- //建立SQL Server链接
- 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;
- 把其它单表数据记录上传
- //CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar, 200).Value = txtDescription.Text;
- 记录文件长度,读取时使用
- //CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt, 8).Value = UpFile.ContentLength;
- Con.Open();
- CmdObj.ExecuteNonQuery();
- Con.Close();
- txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功
- }
- }
- catch (Exception ex)
- {
- txtMessage.Text = ex.Message.ToString();
- }
- }