0
我一直在試圖發現的是,如何將圖像的BLOB存儲到我的數據庫中,而不必先將它保存到文件系統中,直接從服務器的內存中保存。如何將圖像的BLOB保存到sql數據庫中而不保存到文件系統中?
我使用一個sql服務器和其他形式的信息,我有2個圖像需要存儲在數據庫中。我還想知道如何將它們讀出來並將它們轉換回圖像。
在數據庫我有「縮略圖」,它是類型「圖像」。如果我沒有錯,那應該是正確的。
對於圖像上傳我用下面的ASP控制:
<asp:FileUpload ID="_imageUpload" runat="server" />
,因爲我很新的使用數據庫與網站一起特別是我還從來沒有做過這樣的事。
哦,對不起,如果這個問題已被問及已回答。
在此先感謝!
[編輯]
我的整個代碼:
protected void _uploadImageBtn_Click(object sender, EventArgs e)
{
string extension;
// checks if file exists
if (!_imageUpload.HasFile)
{
_resultLbl.Text = "Please, Select a File!";
return;
}
// checks file extension
extension = System.IO.Path.GetExtension(_imageUpload.FileName).ToLower();
if (!extension.Equals(".jpg") && !extension.Equals(".jpeg") && !extension.Equals(".png"))
{
_resultLbl.Text = "Only image files (.JPGs and .PNGs) are allowed.";
return;
}
// checks if image dimensions are valid
if (!ValidateFileDimensions(140, 152))
{
_resultLbl.Text = "Maximum allowed dimensions are: width 1520px and height <= 140px.";
return;
}
int fileLen;
string displayString = "";
// Get the length of the file.
fileLen = _imageUpload.PostedFile.ContentLength;
// Create a byte array to hold the contents of the file.
byte[] input = new byte[fileLen - 1];
input = _imageUpload.FileBytes;
// Copy the byte array to a string.
for (int loop1 = 0; loop1 < fileLen; loop1++)
{
displayString = displayString + input[loop1].ToString();
}
try
{
SqlConnection sqlCn = new SqlConnection("Data Source=localhost;Initial Catalog=database;User ID=user;Password=pw");
string qry = "INSERT INTO Project (thumbnail) VALUES (@thumbnail)";
SqlCommand sqlCom = new SqlCommand(qry, sqlCn);
sqlCom.Parameters.Add("@thumbnail", SqlDbType.Image, input.Length).Value = input;
sqlCn.Open();
sqlCom.ExecuteNonQuery();
sqlCn.Close();
}
catch (Exception)
{
(...)
}
}
public bool ValidateFileDimensions(int aHeight, int aWidth)
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(_imageUpload.PostedFile.InputStream))
{
return (image.Height == aHeight && image.Width == aWidth);
}
}
哎,我試了好幾次,我只是調試它,因爲INSERT總是失敗,發生這種情況,因爲(在這裏你的榜樣)的「字節」數組包含無值,所以它試圖填充NULL,這當然不起作用,因爲它是不允許的。你確定這應該起作用嗎? – webster69 2012-08-15 13:54:33
我該怎麼做?我上面更新了我的代碼,所以你可以看到我做了什麼 – webster69 2012-08-15 14:40:02
我實際上已經這樣做了:'if(!_imageUpload.HasFile) { _resultLbl.Text =「Please,Select a File!」; return; }' – webster69 2012-08-15 14:44:05