.NET MVC 后台接受base64的上传图片
1 #region 配合前端的多张图片上传 2 #region 上传图片方法 3 /// <summary> 4 /// 接口方法 5 /// </summary> 6 /// <param name="img">带 data:image/jpeg;base64,的base64的图片</param> 7 /// <returns>图片路径</returns> 8 [HttpPost] 9 public ActionResult GETaddimg2(String img) 10 { 11 if (img == null) 12 { 13 return Json("空"); 14 } 15 else 16 { 17 return Json(PDUploadImage(img), JsonRequestBehavior.AllowGet); 18 } 19 } 20 #endregion 21 #region 图片转化 22 /// <summary> 23 /// base64 的字符串 24 /// </summary> 25 /// <param name="img"></param> 26 /// <returns>图片转成32的名字</returns> 27 public JsonResult PDUploadImage(string img) 28 { 29 string error = ""; 30 return Json(SaveImage("/Upload/Article", img, ref error), JsonRequestBehavior.AllowGet); 31 } 32 #endregion 33 #region 截取data:image/jpeg;base64,提取图片,并保存图片 34 /// <summary> 35 /// 截取data:image/jpeg;base64,提取图片,并保存图片 36 /// </summary> 37 /// <param name="file_name"></param> 38 /// <param name="img_string">base64的字符串</param> 39 /// <param name="error">错误的图片格式</param> 40 /// <returns>路径 + 图片的名称</returns> 41 private string SaveImage(string file_name, string img_string, ref string error) 42 { 43 //try 44 //{ 45 string[] img_array = img_string.Split(','); 46 byte[] arr = Convert.FromBase64String(img_array[1]); 47 using (MemoryStream ms = new MemoryStream(arr)) 48 { 49 Bitmap bmp = new Bitmap(ms); 50 if (img_array[0].ToLower() == "data:image/jpeg;base64") 51 { 52 bmp.Save(file_name + ".jpg"); 53 return SetImg(Guid.NewGuid().ToString().Replace('-', 'p').Substring(4), "jpg", arr); 54 } 55 else if (img_array[0].ToLower() == "data:image/png;base64") 56 { 57 bmp.Save(file_name + ".png"); 58 return SetImg(Guid.NewGuid().ToString().Replace('-', 'p').Substring(4), "png", arr); 59 } 60 else if (img_array[0].ToLower() == "data:image/gif;base64") 61 { 62 bmp.Save(file_name + ".gif"); 63 return SetImg(Guid.NewGuid().ToString().Replace('-', 'p').Substring(4), "gif", arr); 64 } 65 else 66 { 67 error = "不支持该文件格式。"; 68 return "错"; 69 } 70 } 71 //} 72 //catch (Exception ex) 73 //{ 74 // error = "生成图片发生错误。" + ex.ToString(); 75 // return "错"; 76 //} 77 } 78 #endregion 79 #region 保存图片路径及设置名称 80 /// <summary> 81 /// 保存到文件路径 82 /// </summary> 83 /// <param name="ImgName">保存的文件名称</param> 84 /// <param name="suffix">后缀名</param> 85 /// <param name="arr">base64</param> 86 /// <returns>图片的路径</returns> 87 public string SetImg(string ImgName, string suffix, byte[] arr) 88 { 89 string str3 = System.AppDomain.CurrentDomain.BaseDirectory;//找到相对路径 90 string str4 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//找到相对路径 91 System.IO.File.WriteAllBytes(str3 + "/Upload/Article/" + ImgName + "." + suffix + "", arr); 92 return "/Upload/Article/" + ImgName + "." + suffix + ""; 93 } 94 #endregion 95 #endregion