数据库中表的设计:
存储的是对于的WebService的命名空间和类名,图如下:
namespace PicStore {
/// <summary>
/// ProcessPicStore 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class ProcessPicStore : System.Web.Services.WebService {
[WebMethod(Description = "上传一个地址,由此创建文件")]
public string CreatePath(string path) {
string pathOrg = "upload/" + path;
string realPath = Server.MapPath(pathOrg);
if (!Directory.Exists(realPath)) {
Directory.CreateDirectory(realPath);
}
return realPath;
}
[WebMethod(Description = "存储图片")]
public string UploadFile(byte[] fs, string filename, string path) {
//创建文件
string realPath = CreatePath(path) + "/" + filename;
using (FileStream fss = new FileStream(realPath, FileMode.Create)) {
using (MemoryStream m = new MemoryStream(fs)) {
m.WriteTo(fss);
}
}
return "ok";
}
}
}
主服务器端的上传的一般处理程序
public class upload2 : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/html";
HttpPostedFile file = context.Request.Files[0];
//获取文件名及扩展名
string filename = Path.GetFileName(file.FileName);
string ext_name = Path.GetExtension(file.FileName); //图片扩展名
byte[] b = new byte[file.ContentLength];
using (Stream fs = file.InputStream) {
fs.Read(b, 0, file.ContentLength);
}
string path = GetDir(filename);
#region 分布式图片上传实现方案
BookShop.BLL.ServerInfo bll = new BookShop.BLL.ServerInfo();
//获取有效服务器数量
int count = bll.GetValidServerCount();
int index = Guid.NewGuid().ToString().GetHashCode() % count + 1;
//随机获取服务器
BookShop.Model.ServerInfo model = bll.GetServerInfoByNumber(index);
Type t = Type.GetType(model.WebInstanceName);//获取服务器上对应的webservice的接口
object o = Activator.CreateInstance(t); //反射创建对象
MethodInfo m = t.GetMethod("UploadFile"); //用反射调用方法
context.Response.Write(index+"<br/>");
context.Response.Write(m.Invoke(o, new object[] { b, filename, path }));
context.Response.Write("<br/>"+model.ServerIP);
#endregion
}
/// <summary>
/// 校验扩展名
/// </summary>
/// <returns></returns>
public bool CheckExtName(string ext_name) {
bool b = ext_name.Equals(".jpg", StringComparison.OrdinalIgnoreCase) ||
ext_name.Equals(".png", StringComparison.OrdinalIgnoreCase) ||
ext_name.Equals(".jpeg", StringComparison.OrdinalIgnoreCase);
return b;
}
/// <summary>
/// 目录分离算法
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public string GetDir(string filename) {
int hasCode = filename.GetHashCode();
int dir1 = hasCode & 0xf;
int dir2 = hasCode >> 4 & 0xf;
return dir1 + "/" + dir2;
}
public bool IsReusable {
get {
return false;
}
}
}