Save image with webservice

Asked

Viewed 257 times

2

I already have a webservice for which I pass an image (Base64) and it saved on my server. So far it is working perfectly.

On my screen is this code :

function salvar() {
        var dados = {};

        //Utilizar o toDataURL para converter em Base64
        var base64 = document.getElementById("myCanvas").toDataURL("image/png");

        dados.base64 = base64.substr(base64.indexOf(',') + 1, base64.length);

        var WPath = "face1";

        $.ajax({
            type: 'POST',
            //Chamar o webmethod SalvarImagem em webservice.asmx
            url: "SalvarImagem.asmx/SalvarImagemX",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify(dados, WPath),
            success: function (data) {
                alert(data.d);
            }
            , error: function (xmlHttpRequest, status, err) {
                alert("Ocorreu o seguinte erro:" + xmlHttpRequest.responseText)
            }
        });
    }

And my webservice is like this :

public class SalvarImagem : System.Web.Services.WebService
{

    [WebMethod]
    public string SalvarImagemX(string base64, string WPath)
    {
           //MemoryStream com o base64 recebido por parâmetro
        using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
        {
            //Criar um novo Bitmap baseado na MemoryStream
            using (Bitmap bmp = new Bitmap(ms))
            {
                //Local onde vamos salvar a imagem (raiz do site + /canvas.png)
                //string path = Server.MapPath("/" + WPath + "/canvas.png");
                string path = Server.MapPath("/face2/canvas.png");

                //Salvar a imagem no formato PNG
                bmp.Save(path, ImageFormat.Png);
            }
        }

        return "Imagem foi salva com sucesso";
    }
}
}

My problem is that : As I said it works while I only pass a parameter that is the DATA string. But I also need to pass another string that contains the folder where the image should be saved...

When I put second parameter (Wpath) I started getting the error message below... Can anyone tell me what’s wrong ....??

The following error occurred:

{"Message":"Invalid web service call, Missing value for Parameter: u0027WPath u0027." ,"Stacktrace":" at System.Web.Script.Services.Webservicemethoddata.Callmethod(Object target, Idictionary2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary2 Parameters) r n at System.Web.Script.Services.Resthandler.Invokemethod(Httpcontext context, Webservicemethoddata methodData, Idictionary`2 rawParams) r n at System.Web.Script.Services.Resthandler.Executewebservicecall(Httpcontext context, Webservicemethoddata methodData)","Exceptiontype":"System.Invalidoperationexception"}

3 answers

1

You’re making a mistake because that’s not how you use the JSON.stringify for what you’re intending.

You passed two parameters to him, here:

JSON.stringify(dados, WPath)

According to the documentation, the second parameter of JSON.stringify is the replacer:

Placer: A Function that alters the behavior of the stringification process, or an array of String and Number Objects that serve as a Whitelist for Selecting/Filtering the properties of the value Object to be included in the JSON string.

In a free translation, the replacer would be "A function that alters the behavior of the string transformation process, or a String and Number array that serve as a list to select and filter the properties of the object to be transformed into string".

I was going to show you how to use the second parameter, but that wasn’t the question, so I’m going to leave a possible solution for your AJAX. Exchange the code I mentioned above for the following:

data: '{"base64":"' + dados + '","WPath":"' + WPath + '"}'

I hope it helps you, any doubt put there in the comments

1


To whom it may interest the problem was why it was lacking to put the complement of the variable, it was like this :

data: '{"base64":"' + dados + '","fileName":"' + nomearq + '"}',

But that’s what’s right : data: '{"base64":"' + dados.base64 + '","fileName":"' + nomearq + '"}',

Here’s the record for future sufferers. Abs.

0

Thank you Diego...

I don’t have much experience with AJAX I did what you suggested but is giving a syntax error that I can not identify... follows picture..

erro

  • Okay. I found out... one ',' was missing at the end...

  • Hello, don’t post additional questions as an answer, instead post a comment in a response that generated the question. Did my answer help? Then mark it as accepted. You can also vote on other questions and answers on the site

  • Ola did what you suggested and went on to give this mistake... The following error occurred:{"Message":"The input is not a Valid Base-64 string as it contains a non-base 64 Character, more than two padding characters, or an illegal Character Among the padding characters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.