前端獲取到的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 }