我想測試一個數據庫存儲圖像,所以我做了谷歌搜索,發現這個代碼:數據庫中存儲的圖像在C#中使用asp.net
cs文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data.SqlClient;
using System.IO;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string strImageName = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + strImageName);
Bitmap bNewImage = new Bitmap(strImageName);
FileStream fs = new FileStream(strImageName, FileMode.Open, FileAccess.Read);
//creating byte array to read image
byte[] bImage = new byte[fs.Length];
fs.Read(bImage, 0, Convert.ToInt32(fs.Length));
fs.Close();
fs = null;
string connstr = "Server=WINSP3UE\\SqlExpress;Database=ImageStore;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string strQuery;
strQuery = "insert into [dbo].[ImageStore](id,[ImageContent]) values(" + "1," + " @pic)";//"INSERT INTO ImageStore (ID, ImageContent) values (" + "1," + " @pic)";
SqlParameter ImageParameter= new SqlParameter();
ImageParameter.SqlDbType = SqlDbType.Image;
ImageParameter.ParameterName = "pic";
ImageParameter.Value = bImage;
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add(ImageParameter);
cmd.ExecuteNonQuery();
Response.Write("Image has been added to database successfully");
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
.aspx文件
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" />
</div>
</form>
它應該工作,但它不是,我的意思是它不更新數據庫,表中的值保持爲空。並且消息「圖像已成功上載到數據庫」也沒有出現。我正在使用的數據庫有一個名爲ImageStore的表,其中有兩個屬性ID和ImageContent。
我是新來的asp.net和c#,任何人都可以請檢查代碼的任何錯誤?
您的參數名稱應該是@pic而不是pic。和其他人一樣,你應該通過調試器來運行它。有太多的事情可能會出錯。什麼樣的錯誤信息,你btw? – 2011-04-30 02:37:40