最近我遇到了一个需求,我需要在我的服务器上托管我的网站,而不同客户端的数据库将在那里分别服务器。现在对于数据库中的数据,我可以动态地处理连接字符串。但是,我们保存在服务器机器上的媒体文件呢?如何上传一个服务器上的图像,并将其保存在另一个服务器上使用ASP.NET
我们该如何处理这种情况?
请提出一些建议。
谢谢
最近我遇到了一个需求,我需要在我的服务器上托管我的网站,而不同客户端的数据库将在那里分别服务器。现在对于数据库中的数据,我可以动态地处理连接字符串。但是,我们保存在服务器机器上的媒体文件呢?如何上传一个服务器上的图像,并将其保存在另一个服务器上使用ASP.NET
我们该如何处理这种情况?
请提出一些建议。
谢谢
我想你有两个选择;
现在,仿佛网站服务器被称为服务器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();
}
}
您可以将文件上传到一个文件夹中的服务器1,并创建服务器2中的虚拟目录和此目录的路径将是Server1文件夹。 – Mairaj
谢谢Mairaj,但我也需要在各自的服务器上的图像,即server2。 – Deeps
是的,它可以在两台服务器上访问。 – Mairaj