Fork me on GitHub

前端获取Base64字符串格式图片Ajax到后端处理

前端获取到的Base64字符串格式图片一般都是经过处理的图片,例如:裁剪过后的,这里假设data为获取到的Base64字符串格式图片

Base64格式图片的格式为 “data:image/png;base64,****”逗号之前都是一些说明性的文字,我们只需要逗号之后的就行了
js代码
 1 function uploadFile(data) {
 2         data = data.split(',')[1]
 3         $.ajax({
 4             url: '链接地址',
 5                 type: 'POST',
 6                 data: { 'Data': data },
 7                 dataType: 'JSON',
 8                 success: function (data, textStatus) {
 9                     if (data.Success) {
10                         //自己的处理逻辑
11                     }
12                     else {
13                         console,log("失败");
14                     }
15                 },
16                 error: function (XMLHttpRequest, textStatus, errorThrown) {
17                     console.log(errorThrown);
18                 }
19             })
20         }

后端Action代码

 1 public JsonResult UploadImage()
 2 {
 3     try
 4     {
 5         string base64string = Request["Data"];
 6         byte[] bt = Convert.FromBase64String(base64string);
 7         MemoryStream stream = new MemoryStream(bt);
 8         Bitmap bitmap = new Bitmap(stream);
 9         string tempName = Request.PhysicalApplicationPath + @"\xxxx\" + "b64img_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
10         bitmap.Save(tempName, ImageFormat.Png);
11         //其他逻辑
12         
13         //返回数据
14         return Json(new {Success = true})
15     }
16     catch (Exception ex)
17     {
18         Log.Instance.SaveLog(ex.Message);//日志类自己定义的,可以忽略
19     }
20     return Json(new {Success = false});
21 }

 

posted @ 2018-04-10 14:17  雪山玉龙  阅读(7945)  评论(2编辑  收藏  举报