How to upload object from JavaScript to Rest API

I have a Rest API:

[HttpPost]
[Route("Services/Image/Upload")]
public string Upload([FromBody]GalleryItem galleryItem)
{
    try
    {
        var appSettings = ConfigurationManager.AppSettings["GalleryPath"].ToString();

        using (FileStream fs = new FileStream(appSettings + galleryItem.KeyCode + ".jpg", FileMode.Create))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                byte[] data = Convert.FromBase64String(galleryItem.Base64);
                bw.Write(data);
                bw.Close();
            }
        }
        return "OK";
    }
    catch (Exception ex)
    {
        return ex.ToString();

    }
}

and I call it from my Javascript client like:

var galleryItem = new Object();
galleryItem.Base64 = base64;
galleryItem.KeyCode = '1234';
url = "http://my domain name/api/Services/Image/Upload";
$.ajax({
    type: 'POST',         
    url: url,
    data: JSON.stringify(galleryItem),
    contentType: 'application/json; charset=utf-8',
    dataType: 'text/plain',
    success: function (msg) {
        alert('Image saved successfully !');
    },
    error: function (jqXHR, textStatus, err) {
        $('#error').html('Error: ' + err);
}
});

my model:

public class GalleryItem
{
    public string Base64 { get; set; }
    public string KeyCode { get; set; }
}

I a testing this via a mobile device as I am taking image from camera to send up.

Nothing appears to happen? I just 'Error: error'?

thanks

ADDITIONAL: After porting to a test script (wished I had done that sooner) I found the error is this:

net::ERR_NAME_NOT_RESOLVED

Though why I am unsure as I am calling another method from that api with no issues

Answers:

Answer

Solved!

Thank God!

I changed the url to relative:

url = "/api/Services/Image/Upload";

without prefixing with domain name.

it must have got confused and thought it needed cors? (guess here)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.