2009-04-08 63 views
0

我以前做過這個,但採用了不同的方式。我試圖讓下面的代碼工作。如果我沒有投下「OriginalPhoto」或「Thumbnail」,則會發生錯誤。不允許從數據類型varchar到varbinary(max)的隱式轉換。使用CONVERT函數來運行此查詢。我不明白爲什麼它要求施放。但是,如果我確實投了它,那麼圖像就會以二進制數據格式添加到數據庫中。試圖查看圖像時,出現錯誤「無法顯示給定的數據」。我已經使用SqlDataAdapter將兩個byte []插入到表中,並且工作正常。我想用這個方法,但是我做錯了什麼?Asp.Net將圖像添加到SQL表...我做錯了什麼?

PROFILEGALLERY表包含:

用戶ID爲nvarchar(50)
標題爲nvarchar(10)
OriginalImage VARBINARY(最大值)
ThumbImage VARBINARY(最大值)

protected void AddPhotoToDatabase() 
{ 
    byte[] OriginalPhoto = GetImage(); 
    byte[] Thumbnail = GenerateThumbnail(); 
    string Title = FileUpload1.FileName.ToString(); 
    string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))"; 
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString; 
    SqlConnection conn = new SqlConnection(strCon); 
    SqlCommand comm = new SqlCommand(sql, conn); 
    conn.Open(); 
    comm.ExecuteNonQuery(); 
    conn.Close(); 
} 

protected byte[] GetImage() 
{ 
    byte[] photo = new byte[FileUpload1.PostedFile.ContentLength]; 
    FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length); 
    return photo; 
} 

protected byte[] GenerateThumbnail() 
{ 
    System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream); 
    double thumbwidth = 0; 
    double thumbheight = 0; 
    double imgsz = 150.0; 
    if (imgsz/image.Width < imgsz/image.Height) 
    { 
     thumbwidth = image.Width * (imgsz/image.Width); 
     thumbheight = image.Height * (imgsz/image.Width); 
    } 
    else 
    { 
     thumbwidth = image.Width * (imgsz/image.Height); 
     thumbheight = image.Height * (imgsz/image.Height); 
    } 
    System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0); 
    MemoryStream ms = new MemoryStream(); 
    thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
    return ms.ToArray(); 
} 

回答

3

您應該使用SQL參數:

using(SqlConnection cnn = GetConnection()) { 
    using(SqlCommand cmd = cnn.CreateCommand()) { 
     cmd.CommandText = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES (@UserId, @Title, @OriginalPhoto, @Thumbnail)"; 
     cmd.Parameters.AddWithValue("@UserId", User.Identity.Name); 
     cmd.Parameters.AddWithValue("@Title", Title); 
     cmd.Parameters.AddWithValue("@OriginalPhoto", OriginalPhoto); 
     cmd.Parameters.AddWithValue("@Thumbnail", Thumbnail); 

     cnn.Open(); 
     cmd.ExecuteNonQuery(); 
     cnn.Close(); 
    } 
} 
+0

謝謝!你真棒!哇,這是一個頭痛的問題。我甚至不在乎爲什麼我的方式不起作用。現在我知道爲什麼每個人都這樣做。謝謝! – user84786 2009-04-08 13:16:35

1

不要嘗試將數據構建到插入查詢中。試試這個吧:

string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], 
       [ThumbImage]) VALUES (@userId, @title, @originalImage, @thumbImage)"; 


string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString; 

SqlConnection conn = new SqlConnection(strCon); 
SqlCommand comm = new SqlCommand(sql, conn); 

comm.Parameters.Add(new SqlParameter("@userId", User.Identity.Name)); 
comm.Parameters.Add(new SqlParameter("@title", Title)); 
comm.Parameters.Add(new SqlParameter("@originalImage", OriginalPhoto)); 
comm.Parameters.Add(new SqlParameter("@thumbImage", Thumbnail)); 
1

看看你的代碼,我有點擔心你對SQL注入攻擊是開放的。爲了幫助緩解這一問題,也應該解決您的問題。您需要使用參數化查詢。像

cmd.CommandText="Insert into [ProfileGallery]" + 
       "(UserId,OriginalPhoto) values (@UserId,@OriginalPhoto)"; 
cmd.Parameters.AddWithValue("UserId",User.Identity.Name); 
cmd.Parameters.AddWithValue("OriginalPhoto",OriginalPhoto); 

代碼失敗的原因可以用此示例應用程序中看到的東西:

static void Main(string[] args) 
{ 
    byte[] byteArray = new byte[] { 1, 2, 0 }; 
    Console.WriteLine("This is my byte array: " + byteArray); 
    Console.ReadLine(); 
} 

此輸出這是我的字節數組:System.Byte []

我有點震驚,你可以添加一個字節數組到一個字符串,特別是sicne它只是給了我們這個類型的名字。

+0

哈哈,非常真實。謝謝! – user84786 2009-04-08 13:23:25

0
protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
      { 
       BindData(); 
      } 
     } 
    private void BindData() 
    { 
     SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB"); 
     string strSQL = "Select * from table6"; 
     SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn); 
     DataSet ds = new DataSet(); 
     dt.Fill(ds); 
     grd1.DataSource = ds; 
     grd1.DataBind(); 
     cn.Close(); 
    } 
    protected void btn1_Click(object sender, EventArgs e) 
    { 
     if(fileupload.HasFile) 
     { 

      string imageSrc = "~/Image/" +fileupload.PostedFile.FileName; 
     string ImageName = txt1.Text; 
     SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB"); 
     cn.Open(); 
     string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')"; 
     SqlCommand cmd = new SqlCommand(strSql, cn); 
     cmd.ExecuteNonQuery(); 
     cn.Close(); 
     BindData(); 
     txt1.Text = ""; 
    } 
+0

歡迎來到StackOverflow。你知道這個問題已經在3年前回答了嗎? – RichardTheKiwi 2012-10-19 21:20:56

0

這個簡單的代碼就足以插入圖像到SQL沒有考慮HTTP處理程序

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
      { 
       BindData(); 
      } 
     } 
    private void BindData() 
    { 
     SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB"); 
     string strSQL = "Select * from table6"; 
     SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn); 
     DataSet ds = new DataSet(); 
     dt.Fill(ds); 
     grd1.DataSource = ds; 
     grd1.DataBind(); 
     cn.Close(); 
    } 
protected void btn1_Click(object sender, EventArgs e) 
    { 
     if(fileupload.HasFile) 
     { 

      string imageSrc = "~/Image/" +fileupload.PostedFile.FileName; 
     string ImageName = txt1.Text; 
     SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB"); 
     cn.Open(); 
     string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')"; 
     SqlCommand cmd = new SqlCommand(strSql, cn); 
     cmd.ExecuteNonQuery(); 
     cn.Close(); 
     BindData(); 
     txt1.Text = ""; 
    } 
+0

這是否可以防止SQL注入? – Leigh 2012-10-19 21:44:29