文章内容

2017/3/29 13:29:15,作 者: 黄兵

总结:ASP.NET MVC5中通过HttpWebRequest上传图片文件到服务器

其实使用网页上传图片或者其它文件时,表单为我们简化了文件的上传的过程。但是有时我们想把前台上传过来的文件在保存到服务器的时候同时提交到另外一个服务器地址并保存起来。要实现这个功能要利用HttpWebRequest模拟网页的表单提交过程。今天我就来分享一下我在ASP.NET mvc5中通过HttpWebRequest上传文件到服务器的实现方案。

一、传统的网页上传文件方法

首先我们来看看传统的表单提交过程。

当我们都是通过表单来上传文件。前台html代码:

  1. <form enctype="multipart/form-data" action="/Upload/UploadPic" method="post" id="UploadForm">
  2. <div style="padding:15px; text-align:left;">
  3. <input type="file" style="margin-bottom:10px;" name="UploadImage" id="UploadImage">
  4. <input type="submit" class="btn btn-primary" value="上传">
  5. </div>
  6. </form>


把form标签的加一个enctype="multipart/form-data"属性,后台可以通过Request.Files获取到前台上传过来的文件,并且可以用file.SaveAs(fileFullPath)把文件保存下来。

二、使用HttpWebRequest上传文件到服务器

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.linq;
  6. using System.Net;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Lanhu.Core
  10. {
  11. public class NetHelper
  12. {
  13. /// <summary>
  14. /// 通过HttpWebRequest上传文件到服务器
  15. /// </summary>
  16. /// <param name="url">上传地址</param>
  17. /// <param name="file">文件所有位置</param>
  18. /// <param name="paramName">表单参数名</param>
  19. /// <param name="contentType">文件的contentType</param>
  20. /// <param name="nvc">其他参数集合</param>
  21. /// <returns></returns>
  22. public static string UploadFileByHttpWebRequest(string url, string file, string paramName, string contentType, NameValueCollection nvc)
  23. {
  24. string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
  25. byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
  26. HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
  27. wr.ContentType = "multipart/form-data; boundary=" + boundary;
  28. wr.Method = "POST";
  29. wr.KeepAlive = true;
  30. wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
  31. Stream rs = wr.GetRequestStream();
  32. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
  33. if (nvc != null)
  34. {
  35. foreach (string key in nvc.Keys)
  36. {
  37. rs.Write(boundarybytes, 0, boundarybytes.Length);
  38. string formitem = string.Format(formdataTemplate, key, nvc[key]);
  39. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  40. rs.Write(formitembytes, 0, formitembytes.Length);
  41. }
  42. }
  43. rs.Write(boundarybytes, 0, boundarybytes.Length);
  44. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
  45. string header = string.Format(headerTemplate, paramName, file, contentType);
  46. byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  47. rs.Write(headerbytes, 0, headerbytes.Length);
  48. FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
  49. byte[] buffer = new byte[4096];
  50. int bytesRead = 0;
  51. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  52. {
  53. rs.Write(buffer, 0, bytesRead);
  54. }
  55. fileStream.Close();
  56. byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  57. rs.Write(trailer, 0, trailer.Length);
  58. rs.Close();
  59. WebResponse wresp = null;
  60. var result = "";
  61. try
  62. {
  63. wresp = wr.GetResponse();
  64. Stream stream2 = wresp.GetResponseStream();
  65. StreamReader reader2 = new StreamReader(stream2);
  66. //成功返回的結果
  67. result = reader2.ReadToEnd();
  68. }
  69. catch (Exception ex)
  70. {
  71. if (wresp != null)
  72. {
  73. wresp.Close();
  74. }
  75. }
  76. wr = null;
  77. return result;
  78. }
  79. }
  80. }

上面使用HttpWebRequest采用二进制流的形式模拟一个表单提交过程,这样后台也可以采用传统形式获取传过来的文件。

三、ASP.NET MVC5中一个完整的接收图片文件的Controller

  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Drawing;
  6. using System.Dynamic;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Web;
  13. using System.Web.Mvc;
  14. namespace Lanhu.Admin.Controllers
  15. {
  16. public class UploadController : Controller
  17. {
  18. private string FilePhysicalPath = string.Empty;
  19. private string FileRelativePath = string.Empty;
  20. #region Private Methods
  21. /// <summary>
  22. /// 检查是否为合法的上传图片
  23. /// </summary>
  24. /// <param name="_fileExt"></param>
  25. /// <returns></returns>
  26. private string CheckImage(HttpPostedFileBase imgfile)
  27. {
  28. string allowExt = ".gif.jpg.png";
  29. string fileName = imgfile.FileName;
  30. FileInfo file = new FileInfo(fileName);
  31. string imgExt = file.Extension;
  32. Image img = IsImage(imgfile);
  33. string errorMsg = fileName + ":";
  34. if (img == null)
  35. {
  36. errorMsg = "文件格式错误,请上传gif、jpg、png格式的图片";
  37. return errorMsg;
  38. }
  39. if (allowExt.IndexOf(imgExt.ToLower()) == -1)
  40. {
  41. errorMsg = "请上传gif、jpg、png格式的图片;";
  42. }
  43. //if (imgfile.ContentLength > 512 * 1024)
  44. //{
  45. // errorMsg += "图片最大限制为0.5Mb;";
  46. //}
  47. //if (img.Width < 20 || img.Width > 480 || img.Height < 20 || img.Height > 854)
  48. //{
  49. // errorMsg += "请上传正确尺寸的图片,图片最小为20x20,最大为480*854。";
  50. //}
  51. if (errorMsg == fileName + ":")
  52. {
  53. return "";
  54. }
  55. return errorMsg;
  56. }
  57. /// <summary>
  58. /// 验证是否为真正的图片
  59. /// </summary>
  60. /// <param name="file"></param>
  61. /// <returns></returns>
  62. private Image IsImage(HttpPostedFileBase file)
  63. {
  64. try
  65. {
  66. Image img = Image.FromStream(file.InputStream);
  67. return img;
  68. }
  69. catch
  70. {
  71. return null;
  72. }
  73. }
  74. private string NewFileName(string fileNameExt)
  75. {
  76. return DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileNameExt;
  77. //return Guid.NewGuid().ToString() + fileNameExt;
  78. }
  79. private UploadImgResult UploadImage(HttpPostedFileBase file)
  80. {
  81. UploadImgResult result = new UploadImgResult();
  82. try
  83. {
  84. string fileNameExt = (new FileInfo(file.FileName)).Extension;
  85. //string saveName = GetImageName() + fileNameExt;
  86. //获得要保存的文件路径
  87. String newFileName = NewFileName(fileNameExt);
  88. String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
  89. FilePhysicalPath += ymd + "/";
  90. FileRelativePath += ymd + "/";
  91. String fileFullPath = FilePhysicalPath + newFileName;
  92. if (!Directory.Exists(FilePhysicalPath))
  93. Directory.CreateDirectory(FilePhysicalPath);
  94. file.SaveAs(fileFullPath);
  95. string relativeFileFullPath = FileRelativePath + newFileName;
  96. result.Result = 1;
  97. result.msg = relativeFileFullPath;
  98. }
  99. catch (Exception ex)
  100. {
  101. result.Result = 3;
  102. result.msg = ex.Message;
  103. }
  104. return result;
  105. }
  106. private void showError(string message)
  107. {
  108. Hashtable hash = new Hashtable();
  109. hash["error"] = 1;
  110. hash["message"] = message;
  111. Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
  112. Response.Write(JsonConvert.SerializeObject(hash));
  113. Response.End();
  114. }
  115. #endregion
  116. [HttpPost]
  117. public string UploadPic()
  118. {
  119. Response.ContentType = "text/plain";
  120. List<UploadImgResult> results = new List<UploadImgResult>();
  121. FileRelativePath = System.Configuration.ConfigurationManager.AppSettings["UploadProductImgPath"];
  122. FilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath(FileRelativePath);
  123. if (!Directory.Exists(FilePhysicalPath))
  124. {
  125. Directory.CreateDirectory(FilePhysicalPath);
  126. }
  127. string saveFileResult = string.Empty;
  128. HttpFileCollectionBase files = (HttpFileCollectionBase)Request.Files;
  129. for (int i = 0; i < files.Count; i++)
  130. {
  131. HttpPostedFileBase file = files[i];
  132. UploadImgResult result = null;
  133. string checkResult = CheckImage(file);
  134. if (string.IsNullOrEmpty(checkResult))
  135. {
  136. result = UploadImage(file);
  137. }
  138. else
  139. {
  140. result = new UploadImgResult();
  141. result.Result = 2;
  142. result.msg = checkResult;
  143. }
  144. results.Add(result);
  145. }
  146. string json = JsonConvert.SerializeObject(results);
  147. return json;
  148. }
  149. private void HandleWaterMark(string fileFullPath)
  150. {
  151. bool isWaterMask = Request.Form["watermask"] == "1";
  152. if (isWaterMask)
  153. {
  154. string waterurl = Request.MapPath("/Content/water.png");
  155. //CommonHelper.MakeWatermark(fileFullPath, waterurl, fileFullPath, 4, 95);
  156. }
  157. }
  158. public string FileManagerJson()
  159. {
  160. String aspxUrl = Request.Path.Substring(0, Request.Path.LastIndexOf("/") + 1);
  161. ////根目录路径,相对路径
  162. //String rootPath = "../attached/";
  163. ////根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
  164. //String rootUrl = aspxUrl + "../attached/";
  165. //根目录路径,相对路径
  166. String rootPath = System.Configuration.ConfigurationManager.AppSettings["UploadDir"];
  167. //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
  168. String rootUrl = System.Configuration.ConfigurationManager.AppSettings["UploadDir"];
  169. //图片扩展名
  170. String fileTypes = "gif,jpg,jpeg,png,bmp";
  171. String currentPath = "";
  172. String currentUrl = "";
  173. String currentDirPath = "";
  174. String moveupDirPath = "";
  175. String dirPath = Server.MapPath(rootPath);
  176. String dirName = Request.QueryString["dir"];
  177. if (!String.IsNullOrEmpty(dirName))
  178. {
  179. if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1)
  180. {
  181. return "Invalid Directory name.";
  182. }
  183. dirPath += dirName + "/";
  184. rootUrl += dirName + "/";
  185. if (!Directory.Exists(dirPath))
  186. {
  187. Directory.CreateDirectory(dirPath);
  188. }
  189. }
  190. //根据path参数,设置各路径和URL
  191. String path = Request.QueryString["path"];
  192. path = String.IsNullOrEmpty(path) ? "" : path;
  193. if (path == "")
  194. {
  195. currentPath = dirPath;
  196. currentUrl = rootUrl;
  197. currentDirPath = "";
  198. moveupDirPath = "";
  199. }
  200. else
  201. {
  202. currentPath = dirPath + path;
  203. currentUrl = rootUrl + path;
  204. currentDirPath = path;
  205. moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
  206. }
  207. //排序形式,name or size or type
  208. String order = Request.QueryString["order"];
  209. order = String.IsNullOrEmpty(order) ? "" : order.ToLower();
  210. //不允许使用..移动到上一级目录
  211. if (Regex.IsMatch(path, @"\.\."))
  212. {
  213. Response.Write("Access is not allowed.");
  214. Response.End();
  215. }
  216. //最后一个字符不是/
  217. if (path != "" && !path.EndsWith("/"))
  218. {
  219. Response.Write("Parameter is not valid.");
  220. Response.End();
  221. }
  222. //目录不存在或不是目录
  223. if (!Directory.Exists(currentPath))
  224. {
  225. Response.Write("Directory does not exist.");
  226. Response.End();
  227. }
  228. //遍历目录取得文件信息
  229. string[] dirList = Directory.GetDirectories(currentPath);
  230. string[] fileList = Directory.GetFiles(currentPath);
  231. switch (order)
  232. {
  233. case "size":
  234. Array.Sort(dirList, new NameSorter());
  235. Array.Sort(fileList, new SizeSorter());
  236. break;
  237. case "type":
  238. Array.Sort(dirList, new NameSorter());
  239. Array.Sort(fileList, new TypeSorter());
  240. break;
  241. case "name":
  242. default:
  243. Array.Sort(dirList, new NameSorter());
  244. Array.Sort(fileList, new NameSorter());
  245. break;
  246. }
  247. Hashtable result = new Hashtable();
  248. result["moveup_dir_path"] = moveupDirPath;
  249. result["current_dir_path"] = currentDirPath;
  250. result["current_url"] = currentUrl;
  251. result["total_count"] = dirList.Length + fileList.Length;
  252. List<Hashtable> dirFileList = new List<Hashtable>();
  253. result["file_list"] = dirFileList;
  254. for (int i = 0; i < dirList.Length; i++)
  255. {
  256. DirectoryInfo dir = new DirectoryInfo(dirList[i]);
  257. Hashtable hash = new Hashtable();
  258. hash["is_dir"] = true;
  259. hash["has_file"] = (dir.GetFileSystemInfos().Length > 0);
  260. hash["filesize"] = 0;
  261. hash["is_photo"] = false;
  262. hash["filetype"] = "";
  263. hash["filename"] = dir.Name;
  264. hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
  265. dirFileList.Add(hash);
  266. }
  267. for (int i = 0; i < fileList.Length; i++)
  268. {
  269. FileInfo file = new FileInfo(fileList[i]);
  270. Hashtable hash = new Hashtable();
  271. hash["is_dir"] = false;
  272. hash["has_file"] = false;
  273. hash["filesize"] = file.Length;
  274. hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
  275. hash["filetype"] = file.Extension.Substring(1);
  276. hash["filename"] = file.Name;
  277. hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
  278. dirFileList.Add(hash);
  279. }
  280. Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
  281. //Response.Write(JsonConvert.SerializeObject(result));
  282. //Response.End();
  283. return JsonConvert.SerializeObject(result);
  284. }
  285. }
  286. #region Model
  287. public class UploadImgResult
  288. {
  289. public int Result { set; get; } //1成功,2失败,3异常
  290. public string msg { set; get; }
  291. }
  292. public class NameSorter : IComparer
  293. {
  294. public int Compare(object x, object y)
  295. {
  296. if (x == null && y == null)
  297. {
  298. return 0;
  299. }
  300. if (x == null)
  301. {
  302. return -1;
  303. }
  304. if (y == null)
  305. {
  306. return 1;
  307. }
  308. FileInfo xInfo = new FileInfo(x.ToString());
  309. FileInfo yInfo = new FileInfo(y.ToString());
  310. return xInfo.FullName.CompareTo(yInfo.FullName);
  311. }
  312. }
  313. public class SizeSorter : IComparer
  314. {
  315. public int Compare(object x, object y)
  316. {
  317. if (x == null && y == null)
  318. {
  319. return 0;
  320. }
  321. if (x == null)
  322. {
  323. return -1;
  324. }
  325. if (y == null)
  326. {
  327. return 1;
  328. }
  329. FileInfo xInfo = new FileInfo(x.ToString());
  330. FileInfo yInfo = new FileInfo(y.ToString());
  331. return xInfo.Length.CompareTo(yInfo.Length);
  332. }
  333. }
  334. public class TypeSorter : IComparer
  335. {
  336. public int Compare(object x, object y)
  337. {
  338. if (x == null && y == null)
  339. {
  340. return 0;
  341. }
  342. if (x == null)
  343. {
  344. return -1;
  345. }
  346. if (y == null)
  347. {
  348. return 1;
  349. }
  350. FileInfo xInfo = new FileInfo(x.ToString());
  351. FileInfo yInfo = new FileInfo(y.ToString());
  352. return xInfo.Extension.CompareTo(yInfo.Extension);
  353. }
  354. }
  355. #endregion
  356. }


这个处理上传图片的Controller中UploadPic就是对外公开的Action。要使用这个ASP.NET MVC5的Action上传图片你可以采用网页的表单也可以用上面我讲的用HttpWebRequest。

最后,我们来看看怎么使用我们头面封装的NetHelper把前台上传过来的文件在保存到服务器的时候同时提交到另外一个服务器地址并保存起来。

  1. [HttpPost]
  2. public string UploadPic()
  3. {
  4. string json = "";
  5. Response.ContentType = "text/plain";
  6. List<UploadImgResult> results = new List<UploadImgResult>();
  7. FileRelativePath = System.Configuration.ConfigurationManager.AppSettings["UploadProductImgPath"];
  8. FilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath(FileRelativePath);
  9. if (!Directory.Exists(FilePhysicalPath))
  10. {
  11. Directory.CreateDirectory(FilePhysicalPath);
  12. }
  13. string saveFileResult = string.Empty;
  14. HttpFileCollectionBase files = (HttpFileCollectionBase)Request.Files;
  15. for (int i = 0; i < files.Count; i++)
  16. {
  17. HttpPostedFileBase file = files[i];
  18. UploadImgResult result = null;
  19. string checkResult = CheckImage(file);
  20. if (string.IsNullOrEmpty(checkResult))
  21. {
  22. //上传到本地并返回保存到所在服务器的相对地址
  23. result = UploadImage(file);
  24. //将图片上传到远程的服务器
  25. json=NetHelper.UploadFileByHttpWebRequest(Lanhusoft.Core.AppConfigHelper.ImageHost+"/Upload/UploadPic", Server.MapPath(result.msg), "uploadFileName", file.ContentType, null);
  26. //把远程服务器返回的保存图片相对地址替换成http开头的绝对地址
  27. results = JsonConvert.DeserializeObject<List<UploadImgResult>>(json);
  28. //处理文件在远程服务器和本地服务器路径不一致的问题
  29.                     FileInfo fi = new FileInfo(Server.MapPath(result.msg));
  30.                     var dir=Path.GetDirectoryName(Server.MapPath(results[0].msg));
  31.                     if (!Directory.Exists(dir))
  32.                         Directory.CreateDirectory(dir);
  33.                     fi.MoveTo(Server.MapPath(results[0].msg));
  34.                     
  35.                     return json;
  36. }
  37. else
  38. {
  39. result = new UploadImgResult();
  40. result.Result = 2;
  41. result.msg = checkResult;
  42. results.Add(result);
  43. }
  44. }
  45. json = JsonConvert.SerializeObject(results);
  46. return json;
  47. }

本文转载自:

本文标题:总结:ASP.NET MVC5中通过HttpWebRequest上传图片文件到服务器
本文地址:http://www.lanhusoft.com/Article/406.html

分享到:

发表评论

评论列表