1 public JsonResult HandleImgUpload(User user, System.Web.HttpPostedFileBase fileData, long shopId = 0)
2 {
3 try
4 {
5 System.Drawing.Image img = System.Drawing.Image.FromStream(fileData.InputStream);
6 if (img.Height <= 800 && img.Width <= 600)
7 {
8 // 设置参数
9 HttpWebRequest request = WebRequest.Create(Settings.GetSettingByKey("uploadUrl_img") + user.UserID) as HttpWebRequest;
10 CookieContainer cookieContainer = new CookieContainer();
11 request.CookieContainer = cookieContainer;
12 request.AllowAutoRedirect = true;
13 request.Method = "POST";
14
15 string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
16 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
17 byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("
--" + boundary + "
");
18 byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("
--" + boundary + "--
");
19
20 //请求头部信息
21 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name="file";filename="{0}"
Content-Type:application/octet-stream
", fileData.FileName));
22 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
23
24 byte[] bytes = new byte[fileData.InputStream.Length];
25 fileData.InputStream.Seek(0, SeekOrigin.Begin);
26 fileData.InputStream.Read(bytes, 0, bytes.Length);
27
28 Stream postStream = request.GetRequestStream();
29 postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
30 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
31 postStream.Write(bytes, 0, bytes.Length);
32 postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
33 postStream.Close();
34 //发送请求并获取相应回应数据
35 HttpWebResponse response = request.GetResponse() as HttpWebResponse;
36 //直到request.GetResponse()程序才开始向目标网页发送Post请求
37 Stream instream = response.GetResponseStream();
38 StreamReader sr = new StreamReader(instream, Encoding.UTF8);
39 //返回结果网页(html)代码
40 string content = sr.ReadToEnd();
41 var info = Newtonsoft.Json.JsonConvert.DeserializeObject<UploadFileResult>(content);
42
43 if (info.Result == 0 && info.Info != null)
44 {
45 return Json(new { error = 0, url = info.Info.Url }, JsonRequestBehavior.AllowGet);
46 }
47 else
48 {
49 return Json(new { error = 1, message = info.Msg }, JsonRequestBehavior.AllowGet);
50 }
51 }
52 else
53 {
54 return Json(new { error = 1, message = "文件尺寸超过限制(高:800,宽:600)" }, JsonRequestBehavior.AllowGet);
55 }
56 }
57 catch
58 {
59 return Json(new { error = 1, message = "上传失败" }, JsonRequestBehavior.AllowGet);
60 }
61 }