Reputation: 567
Recently i came across a requirement in which i need to host my website on my server, and the databases for different client will be in there respective servers. Now for data in database i can handle the connection string dynamically. But what about media files which we save on the server machine??
How can we handle this scenario?
Please suggest some ideas.
Thanks
Upvotes: 1
Views: 10239
Reputation: 65
I think you have two options;
now, as if the website server called Server 1, the database server called Server 2.
Option1, you can upload the image to folder on Server 1,the database just store the image name, image path.
//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
//......
}
}
Second, you can directly save the image to database on Server2, the column type can use image, byte,binary or 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 ();
}
}
Upvotes: 0