2015-05-28 46 views
0

最近我遇到了一個需求,我需要在我的服務器上託管我的網站,而不同客戶端的數據庫將在那裏分別服務器。現在對於數據庫中的數據,我可以動態地處理連接字符串。但是,我們保存在服務器機器上的媒體文件呢?如何上傳一個服務器上的圖像,並將其保存在另一個服務器上使用ASP.NET

我們該如何處理這種情況?

請提出一些建議。

謝謝

+0

您可以將文件上傳到一個文件夾中的服務器1,並創建服務器2中的虛擬目錄和此目錄的路徑將是Server1文件夾。 – Mairaj

+0

謝謝Mairaj,但我也需要在各自的服務器上的圖像,即server2。 – Deeps

+0

是的,它可以在兩臺服務器上訪問。 – Mairaj

回答

1

我想你有兩個選擇;

現在,彷彿網站服務器被稱爲服務器1, 稱爲服務器的數據庫服務器2

選項1,您可以上傳圖像到服務器1文件夾,數據庫只存儲映像名稱,圖片路徑。

//get the file name of the posted image 
string imgName = image.FileName.ToString(); 

String path = Server.MapPath("~/ImageStorage");//Path 

//Check if directory exist 
if (!System.IO.Directory.Exists(path)) 
{ 
    System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist 
} 

//sets the image path 
string imgPath = Path.Combine(path, imgName); 

//get the size in bytes that 
int imgSize = image.PostedFile.ContentLength; 


if (image.PostedFile != null) 
{ 

    if (image.PostedFile.ContentLength > 0)//Check if image is greater than 5MB 
    { 
     //Save image to the Folder 
     image.SaveAs(imgPath); 
     //also save image path to database 
     //...... 
    } 

} 

其次,你可以將圖像直接保存到數據庫Server2上,列的類型可以使用圖像,字節,二進制或BLOB

public static void PerisitImage(string path, IDbConnection connection) 
{ 
    using (var command = connection.CreateCommand()) 
    { 
     Image img = Image.FromFile (path); 
     MemoryStream tmpStream = new MemoryStream(); 
     img.Save (tmpStream, ImageFormat.Png); // change to other format 
     tmpStream.Seek (0, SeekOrigin.Begin); 
     byte[] imgBytes = new byte[MAX_IMG_SIZE]; 
     tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE); 

     command.CommandText = "INSERT INTO images(payload) VALUES (:payload)"; 
     IDataParameter par = command.CreateParameter(); 
     par.ParameterName = "payload"; 
     par.DbType = DbType.Binary; 
     par.Value = imgBytes; 
     command.Parameters.Add(par); 
     command.ExecuteNonQuery(); 
    } 
} 
+0

謝謝Jack.li.但是我也需要在各自服務器上的圖像,即server2。 – Deeps

+0

請參閱我的更新,如果圖像保存到數據庫服務器,那麼意味着已經保存到服務器2,您的擔心是什麼? –

+0

謝謝Jack.li.對於之前的評論感到抱歉,它引起了一些混淆。我的意思是我只需要服務器2和文件夾結構中的圖像,而不是數據庫中的圖像。我知道可能的方式可能是在服務器2上有FTP位置或Web服務。是否有其他方式可行? – Deeps

相關問題