Don Del Grande
Don Del Grande

Reputation: 429

Passing an image from JavaScript to C# in an ASP.NET app?

I have an Image variable loaded in a JavaScript app, and I want to pass it to a C# method in my ASP.NET app (so I can store it in a database). The only problem I am having is getting the image's data itself to the C# method. I tried using an AJAX call (it's a GET) with the C#'s method's byte[] parameter set to the Image's .Picture, but the byte[] is empty.

How do I get the image's data from the JavaScript script to the C# method?

UPDATE: I tried copying the image to a canvas using drawImage on the canvas's rendering context, but the image has to come from my local computer, so when I subsequently try to call canvas.toDataURL, it throws a DOM Security error.

I also considered using FileReader to get the data directly rather than loading it as an image, but, for political reasons, I have to support browsers that don't implement FileReader yet.

Am I asking for something that just isn't possible in JavaScript? (There must be a way of doing this (not necessarily in JS), as Facebook implements loading images from the client computer's local file system.)

Upvotes: 0

Views: 6062

Answers (1)

Kiranramchandran
Kiranramchandran

Reputation: 2094

I don't know how you load your image in javascript app. But when i faced the same issue , i did it in the follwing way.

HTML

  <input id="imgInput" type="file"  name="file" />
  <img id="imagePreview" src="" alt="Item Image" width="96" height="80"/>
  <input id="Button1" type="button" value="save image"  onclick="saveimage();"/>

JS

 $(document).ready(function () {
            $("#imgInput").change(function () {

                readURL(this);

            });

        });
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    $('#imagePreview').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        function saveimage() {
            var images = $('#imagePreview').attr('src');
            var ImageSave = images.replace("data:image/jpeg;base64,", "");
            var submitval = JSON.stringify({ data: ImageSave });

            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                datatype: "json",
                data: submitval,
                url: "your url",
                success: function (data) {
                     //code for success
                }
            });
        }

.CS

[WebMethod]
    public static string saveimage(string data) {
        byte[] imgarr = Convert.FromBase64String(data);
         /* Add further code here*/
    }

Upvotes: 3

Related Questions