user3501613
user3501613

Reputation: 610

Upload Image from client side using only jquery and Web Service in ASP

In my application i want to upload some images from client side.I want to do that without any handler. I want to browse the image from client side(local drive) using jquery and want to pass that image to one web service(from jquery itself) and save that image using that service only without using any other handler.

I tried different posts similar to this but none of them satisfying my needs.

I am new to .net and jquery, so whether it is possible, I tried to get the path of the uploaded image but then I understood due to security browser will not gave the actual path from client side.

So whether there is any other way to do this.........

Upvotes: 1

Views: 4780

Answers (2)

sioesi
sioesi

Reputation: 517

I have worked with images from AngularJS rise to asp, and the best way and I run fast for me was to get the code base64 and the webservice transform the image and save it to a specific route.

public string UploadImageUser(string foto) {
    if (foto != "") {
        var regex = new Regex(@ "data:(?<mime>[\w/\-\.]+);(?<encoding>\w+),(?<data>.*)", RegexOptions.Compiled);
        var match = regex.Match(foto);

        var mime = match.Groups["mime"].Value;
        var encoding = match.Groups["encoding"].Value;
        var data = match.Groups["data"].Value;
        try {
            string path = "C://";
            Byte[] bytes = Convert.FromBase64String(data);
            File.WriteAllBytes(path + "example.jpg", bytes);
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}

To find out how to get the base64 code image that the user can select, you can take this solution Solution

The ajax code is simple, depending on how you work your WebService,

$.ajax({
    type: "post",
    url: "http://localhost:8080/myws/UploadImageUser.aspx" ,
    dataType:"json",
    data: foto,
    success: function (response) {
        alert(response);
    },
    error: function(){
     alert('failure');
    }
})

I tried with base64 and i am adding the code here

   var filesSelected = document.getElementById("inputFileToLoad").files;
    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileReader = new FileReader();
        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            var base64 = srcData;
            //jpeg or png
            base64 = base64.replace('data:image/jpeg;base64,', '');
            $.ajax({
                type: "POST",
                //url: AQ.AMT.Url + "/Home/StoreImage",
                url: "DempService.asmx/StoreImage",
                //async: false,
                data: "{'base64':'" + base64 + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (Data) {
                    alert('ok');
                 },
                error: function (e) {

                }
            });
        }
        fileReader.readAsDataURL(fileToLoad);
    }

in service

    [WebMethod]
    public bool StoreImage(string base64)
    {
        //ExportPptString obj = new ExportPptString();
        string downloadToken = Guid.NewGuid().ToString();
        //extension we have to pass
        string filepath = Server.MapPath("~/Download/" + downloadToken + ".jpeg");
        try
        {
            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
            {
                using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(ms))
                {
                    bm2.Save(filepath);
                }

            }

        }
        catch (Exception ex)
        {

        }

        return true;
    }

Upvotes: 1

Jaylem Chaudhari
Jaylem Chaudhari

Reputation: 106

Try this code. May this code will help you Create ajax POST request for your Web Service.

<script type="text/javascript">
$(document).ready(function () {
   $('#btnUploadFile').on('click', function () {
      var data = new FormData();
      var files = $("#fileUpload").get(0).files;
      // Add the uploaded image content to the form data collection
      if (files.length > 0) {
           data.append("UploadedImage", files[0]);
      }

      // Make Ajax request with the contentType = false, and procesDate = false
      var ajaxRequest = $.ajax({
           type: "POST",
           url: "/api/fileupload/uploadfile",
           contentType: false,
           processData: false,
           data: data
           });

      ajaxRequest.done(function (xhr, textStatus) {
                    // Do other operation
             });
   });
});
</script>

You will get file content in web request

// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

http://www.codeproject.com/Articles/806075/File-Upload-using-jQuery-AJAX-in-ASP-NET-Web-API

Upvotes: 3

Related Questions