前端JS
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#代码:
///
/// 图像转换为Base64编码
///
/// 图像
/// 图像格式
/// 出现异常时是否抛出
///
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
如果你用的是tomcat 报request header too large 的错,就在tomcat的config/server.xml里设置最大头大小
非得用ajax吗
有一别人的解决类似情况的链接,也许对你有帮助:
ajax的post提交参数长度超出限制的解决办法
可以看看是否有帮助。如果有需要,请继续交流(有段时间没有用ajax之类的东西了,有些生疏)。谢谢