我们用NET+EF+MVC开发接口的时候,经常会遇到接收Base64字符串(图片),并将Base64字符串图片post到图片服务器,一般来讲有同步和异步方法,同步的话图片会实时上传到图片服务器,但消耗网络带宽的资源较大,异步上传,消耗网络资源较小,缺点是网络不好的时候会上传不成功,同步和异步没有优劣之分,只是适合不同场景,下来笔者先介绍同步上传的方法(下一篇讲解异步上传方法):
一、同步上传方法(OfflineUpdatehandexamination)
try
{
if(!string.IsNullOrEmpty(item.handexaminationBase64))
{
var ImagesBrowseServer = System.Web.Configuration.WebConfigurationManager.AppSettings["ImagesBrowseServer"].ToString();
#region 图片post到图片服务器
string url7 = "" + ImagesBrowseServer + "/Common/SaveBase64Image";
//string url7 = "http://127.0.0.1/Common/SaveBase64Image";
WebRequest request7 = WebRequest.Create(url7);
request7.Method = "POST";
//post传参数
string postdata = "strBase64=" + HttpContext.Current.Server.UrlEncode(item.handexaminationBase64) + "&subsidiary_id=" + item.subsidiary_id + "&KindergartenID=" + item.KindergartenID + "&Catalog=handexamination";
byte[] bytes = Encoding.ASCII.GetBytes(postdata);
request7.ContentType = "application/x-www-form-urlencoded";
request7.ContentLength = postdata.Length;
Stream sendStream = request7.GetRequestStream();
sendStream.Write(bytes, 0, bytes.Length);
sendStream.Close();
//得到返回值
WebResponse response7 = request7.GetResponse();
string OrderQuantity = new StreamReader(response7.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
var json = JsonConvert.DeserializeObject
string image_path = json.photourl;
#endregion 图片post到图片服务器
#region 写入手检图片
if (!string.IsNullOrEmpty(image_path))
{
decimal detection_record_img_id = WisdomStarts.Common.Utils.GenerateIntID();
hx_detection_record_img img = new hx_detection_record_img();
img.detection_record_img_id = detection_record_img_id;
img.detection_record_id = 0;
img.image_path = image_path;
img.image_type = 1;
img.createtime = item.testingdate;
img.NewEnrolmentID = item.NewEnrolmentID;
img.testingtype = testingtype;
img.testingdate = item.testingdate.Date;
ef.hx_detection_record_img.Add(img);
ef.SaveChanges();
}
#endregion 写入手检图片
}
}
catch (Exception ee)
{
//WisdomStarts.Common.Log.NetLog.WriteTextLog("ee", ee.ToString());
}
二、将base64编码的字符串转为图片并保存
#region 将base64编码的字符串转为图片并保存
///
/// 将base64编码的字符串转为图片并保存
///
///
///
///
///
///
///
///
[HttpPost]
public ActionResult SaveBase64Image(string strBase64, string Catalog = "images", decimal subsidiary_id = 0, decimal KindergartenID = 0)
{
var str = "";
if (subsidiary_id > 0 && KindergartenID > 0)
{
try
{
string filePath = "/hx001/" + subsidiary_id + "/" + KindergartenID + "/" + Catalog + "/";
//string newFileName = Guid.NewGuid().ToString();
var fileExt = "jpg";
string fileName = Guid.NewGuid().ToString() + "." + fileExt;
//Log.Debug("filePath:" + filePath + fileName);
string strbase64 = strBase64.Substring(strBase64.IndexOf(',') + 1);
strbase64 = strbase64.Trim('\0');
//Log.Debug("strbase64:" + strbase64);
byte[] arr = Convert.FromBase64String(strbase64);
using (MemoryStream ms = new MemoryStream(arr))
{
//Log.Debug("进入了MemoryStream");
Bitmap bmp = new Bitmap(ms);
if (!Directory.Exists(Server.MapPath(filePath)))
{
//Log.Debug("没有Directory");
Directory.CreateDirectory(Server.MapPath(filePath));
}
//if (!Directory.Exists(filePath))
// Log.Debug("没有Directory");
//Directory.CreateDirectory(filePath);
//新建第二个bitmap类型的bmp2变量。
Bitmap bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
//将第一个bmp拷贝到bmp2中
Graphics draw = Graphics.FromImage(bmp2);
draw.DrawImage(bmp, 0, 0);
draw.Dispose();
//Log.Debug("保存图片前");
bmp2.Save(Server.MapPath(filePath + fileName), System.Drawing.Imaging.ImageFormat.Jpeg);
//Log.Debug("保存图片后");
//bmp.Save("test.bmp", ImageFormat.Bmp);
//bmp.Save("test.gif", ImageFormat.Gif);
//bmp.Save("test.png", ImageFormat.Png);
ms.Close();
//return Content(filePath + fileName);
str = filePath + fileName;
}
}
catch(Exception ex)
{
//WisdomStarts.Common.Log.NetLog.WriteTextLog("SaveBase64Image上传图片错误", ex.ToString());
//WisdomStarts.Common.Log.NetLog.WriteTextLog("SaveBase64Image上传图片错误_strBase64", strBase64);
return Content("{\"status\":\"N\",\"msg\":\"上传失败!\",\"photourl\":\"\"}", "text/json");
}
}
if (str != "")
{
return Content("{\"status\":\"Y\",\"msg\":\"上传成功!\",\"photourl\":\"" + str + "\"}", "text/json");
}
else
{
return Content("{\"status\":\"N\",\"msg\":\"上传失败!\",\"photourl\":\"\"}", "text/json");
}
}
#endregion 将base64编码的字符串转为图片并保存
留言与评论(共有 0 条评论) “” |