【问题标题】:How to save an image from a base64 string passed through ajax request using c# webmethod如何使用 c# webmethod 从通过 ajax 请求传递的 base64 字符串保存图像
【发布时间】: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


    【解决方案1】:
    [System.Web.Services.WebMethod]
    public string UploadImage(string base64Image,string ImageName)
    {
        string path =Server.MapPath("~/images/");
          if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
        path+=ImageName;
        byte[] fileByte = Convert.FromBase64String(base64Image);
        using (FileStream _FileStream = new FileStream(path, FileMode.Create, 
       FileAccess.Write))
        {
                    _FileStream.Write(fileByte, 0, fileByte.Length);
        }
      return "/images/"+ImageName;
    
    }
    

    【讨论】:

    • 同样的错误:{"Message":"传入的对象无效,应为 \u0027:\u0027 或 \u0027}\u0027。(132): {base64Image:\u0027����\u0006 �Exif\u0000\u0000MM\u0000*...}。我不能写所有的消息,因为太长了。
    猜你喜欢
    • 2015-06-28
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多