我有一個批量上傳對象,用於一次批量上傳25-40個圖像文件。每個圖像的大小約爲100-150 kb。如果記錄存在於數據庫中,請更新單個列
在上傳過程中,我爲每個循環創建了一個採用圖像文件名(不包括文件擴展名)將其寫入名爲「sku」的列的循環。另外,對於每個上傳的文件,日期都會記錄到一個名爲DateUpdated的列中,以及一些圖像路徑數據。
這裏是我的C#代碼:
protected void graphicMultiFileButton_Click(object sender, EventArgs e)
{
//graphicMultiFile is the ID of the bulk uploading object (provided by Dean Brettle: http://www.brettle.com/neatupload )
if (graphicMultiFile.Files.Length > 0)
{
foreach (UploadedFile file in graphicMultiFile.Files)
{
//strip ".jpg" from file name (will be assigned as SKU)
string sku = file.FileName.Substring(0, file.FileName.Length - 4);
//assign the directory where the images will be stored on the server
string directoryPath = Server.MapPath("~/images/graphicsLib/" + file.FileName);
//ensure that if image existes on server that it will get overwritten next time it's uploaded:
file.MoveTo(directoryPath, MoveToOptions.Overwrite);
//current sql that inserts a record to the db
SqlCommand comm;
SqlConnection conn;
string connectionString = ConfigurationManager.ConnectionStrings["DataConnect"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("INSERT INTO GraphicsLibrary (sku, imagePath, DateUpdated) VALUES (@sku, @imagePath, @DateUpdated)", conn);
comm.Parameters.Add("@sku", System.Data.SqlDbType.VarChar, 50);
comm.Parameters["@sku"].Value = sku;
comm.Parameters.Add("@imagePath", System.Data.SqlDbType.VarChar, 300);
comm.Parameters["@imagePath"].Value = "images/graphicsLib/" + file.FileName;
comm.Parameters.Add("@DateUpdated", System.Data.SqlDbType.DateTime);
comm.Parameters["@DateUpdated"].Value = DateTime.Now;
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
}
上傳圖像後,經理會回去,然後重新上傳先前已上傳的圖片。
這是因爲這些產品圖像總是在進行修改和改進。
對於每個新的/改進的圖像,文件名和擴展名將保持不變 - 因此,當圖像321-54321.jpg第一次上傳到服務器時,該圖像的新/改進版本仍將具有圖像文件名稱爲321-54321.jpg。
我不能肯定地說文件大小是否會保持在100-150KB範圍內。我會假設圖像文件的大小最終會增長。
當圖像上傳(再次)時,那個圖像的數據庫中當然會存在一條記錄。 什麼是最好的辦法:
- 檢查數據庫的現有記錄(存儲過程或SqlDataReader對象或創建一個DataSet ...?)
- 然後,如果記錄存在,簡單地更新記錄,以便DateUpdated列獲取今天的日期。
- 如果不存在任何記錄,請按正常方式對記錄執行插入操作。
需要考慮的事情:
如果記錄存在,我們就會讓實際圖像上傳。它將簡單地覆蓋現有圖像,以便新版本顯示在網頁上。
我們在託管環境(DiscountAsp)上使用SQL Server 2000。
我使用C#編程。
上傳過程將由大約2位經理每月幾次使用(每個) - 這對我來說不是一個使用的分配。
雖然我是一個jr。開發人員,我猜測存儲過程將是一條路。看起來效率更高 - 做這個記錄檢查每個循環...但不知道。編寫一個sproc需要額外的幫助,因爲我沒有太多的經驗。
謝謝大家...
感謝撕裂。你的商店程序代碼看起來更好,我想出了。讓我給它一個測試。 - 道格 – Doug 2009-10-08 13:59:11