发布网友 发布时间:2022-04-19 12:44
共5个回答
热心网友 时间:2023-10-24 23:29
前端JS
var reader = new FileReader();
reader.onload = function (e) {
//图片base数据
var imgBaseData = e.target.result;
var pos = imgBaseData.indexOf("4")+2;
imgBaseData = imgBaseData.substring(pos, imgBaseData.length - pos);//去掉Base:开头的标识字符
$.ajax({
type: "POST",
url: "http://imginapi.com/image/AddImage",
async: false,
xhrFields: { withCredentials: true },
data: { 'baseStrImgData': imgBaseData, '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>
/// 图像转换为Base编码
/// </summary>
/// <param name="image">图像</param>
/// <param name="format">图像格式</param>
/// <param name="throwException">出现异常时是否抛出</param>
/// <returns>转换成功返回其Base编码;失败返回空串</returns>
public static string ImageToBase(System.Drawing.Image image, ImageFormat format, OPResult opRes, bool throwException = false)
{
return ExceptionHelper.ExceptionRecord(() =>
{
string baseString = "";
try
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
baseString = Convert.ToBaseString(imageBytes);
}
}
catch (Exception ex)
{
throw new Exception("将图片转成base字符串时出现异常:" + ex);
}
return baseString;
}, opRes, throwException);
}
热心网友 时间:2023-10-24 23:30
前端生成的代码最终格式如下:
data:image/png;base,xxxxxxxxxx...........
后端这样解码
base=base.Replace("data:image/png;base,", "");
byte[] bytes =Convert.FromBaseString(base);
MemoryStream memStream = new MemoryStream(bytes);
BinaryFormatter binFormatter = new BinaryFormatter;
return(System.Drawing.Image)binFormatter.Deserialize(memStream);
string baseStr = "图片的BASE字符串";
byte[] bytes = System.Convert.FromBaseString(baseStr);
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
热心网友 时间:2023-10-24 23:30
如果你用的是tomcat 报request header too large 的错,就在tomcat的config/server.xml里设置最大头大小
热心网友 时间:2023-10-24 23:31
非得用ajax吗
热心网友 时间:2023-10-24 23:31
有一别人的解决类似情况的链接,也许对你有帮助:
ajax的post提交参数长度超出*的解决办法
可以看看是否有帮助。如果有需要,请继续交流(有段时间没有用ajax之类的东西了,有些生疏)。谢谢