How to save an image from a base64 string passed through ajax request using c# webmethod

时间:2019-01-07 13:48:35

标签: c# jquery ajax image httpresponse

I want to upload an image when i select it from an input file control. How can i upload it, with async process and refresh the link in the page when finish the upload.

I have already created the ajax request that call a c# WebMethod, but my problem is, how can i pass the image as a json variable to my WebMethod. I tryied to convert the image to base64 string, but when i send it, iis send me error that the request is invalid.

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!");
        }
    });
}

This is the WebMethod

[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";
}

stackTrace from iis

at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, 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) at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)

sorry for the unindented stack trace but is more readable in this form

Have an idea to save this image with a WebMethod?

P.s. WebMethod is necessary because i need to manipulate image, and do some operation with a database.

1 个答案:

答案 0 :(得分:0)

[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;

}