如何使用ASP.NET在一台服务器上上传图像并将其保存在另一台服务器上
本文关键字:服务器 一台 保存 存在 NET ASP 何使用 图像 | 更新日期: 2023-09-27 17:50:55
最近我遇到了一个要求,我需要在我的服务器上托管我的网站,不同客户端的数据库将在那里各自的服务器。现在,对于数据库中的数据,i可以动态地处理连接字符串。但是我们保存在服务器上的媒体文件呢?
我们如何处理这种情况?
请提一些建议。
谢谢
我认为你有两个选择;
现在,如果网站服务器称为服务器1,数据库服务器服务器2
Option1,您可以将图像上传到Server 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上的数据库中,列类型可以使用image、byte、binary或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 ();
}
}