在图片上传时,选择存放图片服务器,将文件发送到不同 服务器上存储,实现简单的分布式存储
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();
//省略了判断服务器状态
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();
}
}
}
}