asp.net图片分布式存储

在图片上传时,选择存放图片服务器,将文件发送到不同 服务器上存储,实现简单的分布式存储

public ActionResult UploadFile()

        {
            HttpPostedFileBase file = Request.Files["image"];
            //省略了文件的判断,如文件类型,大小等
            string imageName = Path.GetFileName(Server.MapPath(file.FileName));
            string imageEXt = Path.GetExtension(Server.MapPath(file.FileName));
            //随机算法,得到上传的图片存放到那个服务器上
            //随机产生一个数,用这个随机数对可用服务器数取余数,余数即为存储服务器集合的索引值,通过索引得到服务器信息
            Random r = new Random();
            int n = r.Next();            

            ImageServerStoreEntities db = new ImageServerStoreEntities();

           //省略了判断服务器状态

            List<ServerInfo> list = db.ServerInfo.ToList();
            int id = n % list.Count;
            string host = list[id].ServerAddress;
            //将服务器地址作为参数传过去,减少查询数据库的次数
            //要将url地址进行编码,再传递
            string url = "/uploadImage.ashx?server=" + HttpUtility.UrlEncode(host) + "&Serverid=" + list[id].ServerID + "&Ext=" + imageEXt;
            WebClient client = new WebClient();
            string urlAddress = host + url;
            //想服务器上发送图片数据
            client.UploadData(urlAddress, StreamToBytes(file.InputStream));
            return Content("上传成功");
        }

        /// <summary>
        /// 将文件流转成字节数组
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;

        }



部署在图片服务器上的一般处理程序,用来接收传递过来的图片数据,存放到本地并更新数据库中图片信息表

public class uploadImage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        //对接收到的服务器地址进行解码
        string server = HttpUtility.UrlDecode(context.Request["server"]);
        string serverID = context.Request["Serverid"];
        string fileExt = context.Request["Ext"];
        //创建文件夹存储图片,尽量不要将图片都放在一个文件夹中
        //当一个文件夹中文件很多时,加载时速度会很慢
        string dir = "/UploadFiles/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
        Directory.CreateDirectory(context.Server.MapPath(dir));
        string name = Guid.NewGuid().ToString() + fileExt;
        string fileName = context.Server.MapPath(dir) + name;
        //获取传过来的图片数据流
        Stream s = context.Request.InputStream;
        byte[] bytes = new byte[s.Length];
        //将数据流转成字节数组
        s.Read(bytes, 0, bytes.Length);
        // 设置当前流的位置为流的开始
        s.Seek(0, SeekOrigin.Begin);
        //把byte[]写入文件
        FileStream fs = new FileStream(fileName, FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(bytes);
        bw.Close();
        fs.Close();
        //将图片的完整路径存入图片数据表中
        string sql = "insert into ImageInfo(ImageUrl,ServerID)  values('" + server + dir + name + "',"+int.Parse(serverID)+")";
        InsertData(sql);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    protected void InsertData(string sql)
    {
        string connstr = System.Configuration.ConfigurationManager.AppSettings["connstr"];
        using (SqlConnection con = new SqlConnection(connstr))
        {
            con.Open();
            using (SqlCommand com = new SqlCommand())
            {
                com.Connection = con;
                com.CommandText = sql;
                com.ExecuteNonQuery();
            }
        }
    }

}

版权声明
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值