//webclient应用
MyImageServerEntities db = new MyImageServerEntities();
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload()
{
HttpPostedFileBase file = Request.Files["fileUp"];
string fileName = Path.GetFileName(file.FileName);
string fileExt = Path.GetExtension(fileName);
if (fileExt == ".jpg")
{
var list=db.ImageServerInfo.Where<ImageServerInfo>(u => u.FlgUsable == true).ToList();//找出可用的图片服务器.
int count = list.Count();
Random random = new Random();
int r = random.Next();
int i = r % count;
string serverUrl = list[i].ServerUrl;
int serverId = list[i].ServerId;
string url = "http://"+serverUrl+"/FileUp.ashx?serverId="+serverId+"&fileExt="+fileExt;
WebClient webClient =new WebClient();
webClient.UploadData(url, StreamToBytes(file.InputStream)); }
return Content("ok"); }
public ActionResult ShowImage()
{
var list= db.ImageServerInfo.Where<ImageServerInfo>(c=>c.FlgUsable==true).ToList();
ViewData["imageServerList"] = list;
return View();
}
private byte[] StreamToBytes(Stream stream)
{
byte[]buffer=new byte[stream.Length];
stream.Read(buffer, , buffer.Length);
stream.Seek(, SeekOrigin.Begin);
return buffer;
}
context.Response.ContentType = "text/plain";
int serverId = int.Parse(context.Request["serverId"]);
string fileExt = context.Request["fileExt"];
string dir = "/ImagePath/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
Directory.CreateDirectory(Path.GetDirectoryName(context.Request.MapPath(dir)));
string newfileName = Guid.NewGuid().ToString();
string fullDir = dir + newfileName + fileExt;
using (FileStream fileStream = File.Open(context.Request.MapPath(fullDir), FileMode.OpenOrCreate))
{
context.Request.InputStream.CopyTo(fileStream);
MyImageServerEntities db = new MyImageServerEntities();
ImageInfo imageInfo = new ImageInfo();
imageInfo.ImageName = fullDir;
imageInfo.ImageServerId = serverId;
db.ImageInfo.Add(imageInfo);
db.SaveChanges(); }
//httpclient 应用
创建并初始化对象:
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 读集合:
HttpResponseMessage response = client.GetAsync(url).Result;
var userList = response.Content.ReadAsAsync<IEnumerable<数据类型>>().Result; 根据编号读对象
HttpResponseMessage response1 = client.GetAsync(url).Result;
var userInfo = response1.Content.ReadAsAsync<数据类型>().Result; 增加:
HttpResponseMessage response = client.PostAsJsonAsync("api/userinfo", userInfo).Result;
使用response.IsSuccessStatusCode判断是否成功
使用response.Content.ToString()获取返回值 修改:
HttpResponseMessage response = client.PutAsJsonAsync("api/userinfo/"+userInfo.UserId, userInfo).Result;
使用response.IsSuccessStatusCode判断是否成功
使用response.Content.ToString()获取返回值 删除:
HttpResponseMessage response = client.DeleteAsync("api/userinfo/" + uid).Result;
使用response.IsSuccessStatusCode判断是否成功
使用response.Content.ToString()获取返回值