samedi 28 avril 2018

Return JSON instead of XML from web service using Ajax while 'contentType' is 'false'

I made an ajax call to send an image file to one of my web service (.asmx) methods. everything's okay, but the problem is that the web service returns XML instead of JSON because I HAVE TO set 'contentType' to 'false', otherwise file can't be sent. (if I set contentType to application/json; charset=utf-8, it returns json but I can't do that because I'm sending a file.)

This is my JS:

function setAvatar(imageFile, successCallback) {
var formData = new FormData();
formData.append("UploadedAvatar", imageFile);
$.ajax({
    type: "POST",
    url: "/Services/UserService.asmx/SetAvatar",
    contentType: false,
    processData: false,
    dataType: 'json',
    data: formData,
    success: function (result) {
        alert(result.d);
        alert(result.d.IsSuccessful);
        if (typeof successCallback === 'function')
            successCallback(result);
    }
});

and the web service method:

        [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public Result SetAvatar()
    {
        HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
        Image avatar = Image.FromStream(postedFile.InputStream, true, true);
        avatar = new Bitmap(avatar, new Size(150, 150));
        avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

        return new Result(true, Messages.AvatarSavedSuccessfully);
    }




Aucun commentaire:

Enregistrer un commentaire