【发布时间】:2019-06-02 04:37:23
【问题描述】:
当我从输入文件控件中选择图像时,我想上传图像。 我如何上传它,使用异步过程并在完成上传后刷新页面中的链接。
我已经创建了调用 c# WebMethod 的 ajax 请求,但我的问题是,如何将图像作为 json 变量传递给我的 WebMethod。 我尝试将图像转换为 base64 字符串,但是当我发送它时,iis 向我发送请求无效的错误。
function getBase64(file, cb) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function () {
console.log(reader.result);//outputs random looking characters for the image
// Return the result in the callback
cb(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var imgbase64="";
function caricaImmagine(inputFile) {
var _image = $(inputFile)[0].files[0];
getBase64(_image, function (result) {
sendData(result);
});
}
function sendData(data) {
imgbase64=data
$.ajax({
type: 'post',
url: '/admin/ajax_handler.aspx/uploadImgVarianti',
data: "{imgBase64:'"+data+"'}",
success: function (status) {
alert(status["d"])
},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function () {
alert("Whoops something went wrong!");
}
});
}
这是网络方法
[System.Web.Services.WebMethod]
public static string uploadImgVarianti(string imgBase64)
{
byte[] data = Convert.FromBase64String(imgBase64);
string decodedString = Encoding.UTF8.GetString(data);
HttpContext context = HttpContext.Current;
context.Response.Write(decodedString);
return "ok";
}
来自 iis 的堆栈跟踪
在 System.Web.Script.Serialize.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth) 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串输入, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input ) 在 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) 在 System.Web.Script.Services.RestHandler 的 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer 序列化程序)。 ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)
抱歉没有缩进的堆栈跟踪,但这种形式更具可读性
有使用 WebMethod 保存此图像的想法吗?
附: WebMethod 是必要的,因为我需要对图像进行操作,并对数据库进行一些操作。
【问题讨论】:
标签: c# jquery ajax image httpresponse