前端将图片转换为base64位,使用ajax传递到后台,但是图片经过base64转换成字符串后非常长,无法使用ajax
var reader = new FileReader();
reader.onload = function (e) {
//图片base64数据
var imgBase64Data = e.target.result;
var pos = imgBase64Data.indexOf("4")+2;
imgBase64Data = imgBase64Data.substring(pos, imgBase64Data.length - pos);//去掉Base64:开头的标识字符
$.ajax({
type: "POST",
url: "http://imginapi.com/image/AddImage",
async: false,
xhrFields: { withCredentials: true },
data: { 'base64StrImgData': imgBase64Data, 'imgFormat': fileext},
dataType: "text",
success: function (data) {
alert(data);
domUtils.on(iframe, 'load', callback);
},
error: function (err) {
alert("error");
alert(err.responseText);
}
});
return;
};
reader.readAsDataURL(input.files[0]);
后台C#代码:
/// <summary>
/// 图像转换为Base64编码
/// </summary>
/// <param name="image">图像</param>
/// <param name="format">图像格式</param>
/// <param name="throwException">出现异常时是否抛出</param>
/// <returns>转换成功返回其Base64编码;失败返回空串</returns>
public static string ImageToBase64(System.Drawing.Image image, ImageFormat format, OPResult opRes, bool throwException = false)
{
return ExceptionHelper.ExceptionRecord(() =>
{
string base64String = "";
try
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
base64String = Convert.ToBase64String(imageBytes);
}
}
catch (Exception ex)
{
throw new Exception("将图片转成base64字符串时出现异常:" + ex);
}
return base64String;
}, opRes, throwException);
}
前端生成的代码最终格式如下:
data:image/png;base64,xxxxxxxxxx...........
后端这样解码
base64=base64.Replace("data:image/png;base64,", "");
byte[] bytes =Convert.FromBase64String(base64);
MemoryStream memStream = new MemoryStream(bytes);
BinaryFormatter binFormatter = new BinaryFormatter;
return(System.Drawing.Image)binFormatter.Deserialize(memStream);
string base64Str = "图片的BASE64字符串";
byte[] bytes = System.Convert.FromBase64String(base64Str);
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
{return System.Drawing.Image.FromStream(ms);}
ajax({,url : form.action,,type : "POST",,data : formData,
dataType:"text",,processData : false,,success:function(data).window.location.href="${ctx}"+data;
xhr:function//在jquery函数中直接使用ajax的XMLHttpRequest对象
var xhr = new XMLHttpRequest
xhr.upload.addEventListener