如何使用ASP.NET在一台服务器上上传图像并将其保存到另一台服务器上

问题描述 投票:0回答:1

最近我遇到了一个要求,我需要在我的服务器上托管我的网站,不同客户端的数据库将在各自的服务器中。现在对于数据库中的数据,我可以动态处理连接字符串。但是我们保存在服务器机器上的媒体文件呢?

我们如何处理这种情况?

请提出一些想法。

谢谢

c# asp.net .net-3.5 server asp.net-3.5
1个回答
0
投票

我认为你有两种选择;

现在,好像网站服务器名为Server 1,数据库服务器名为Server 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上的数据库,列类型可以使用图像,字节,二进制或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 ();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.