1

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.........

user3501613
  • 596
  • 7
  • 28

2 Answers2

2

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

  • Can You tell the difference between the above method and this method... – user3501613 Oct 07 '16 at 09:23
  • 1
    @user3501613 only difference in both code is request header and image format. above code will post image data with base64 conversion and you will get as method param, and in this code file data will come as request param – Jaylem Chaudhari Oct 07 '16 at 09:42
  • So in above method 2 conversion needed image-BASE64 and vice versa. so i think this will reduce that burden... – user3501613 Oct 07 '16 at 10:09
1

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;
    }
Community
  • 1
  • 1
sioesi
  • 497
  • 1
  • 5
  • 20
  • So first I will convert that image into base64 then I will pass that to web service, I know how to convert a image to base64 but i don't know how to pass that thing to service,can u give that ajax call.. – user3501613 Oct 06 '16 at 12:23
  • As you're working on your asp? you have code for example as receive data? @user3501613 – sioesi Oct 06 '16 at 12:31
  • Edit my post @user3501613 – sioesi Oct 06 '16 at 12:45
  • I used different function in web service can You tell which one is better i am adding my code with your answer – user3501613 Oct 06 '16 at 13:36
  • can u tell what is the difference in both web methods. – user3501613 Oct 06 '16 at 13:46
  • 1
    @user3501613 Here we can find the difference, there are different types of headers in formats of images. But in this case, as we are working with images in base64 code, I think both solutions serves. http://stackoverflow.com/questions/22486316/bitmap-save-vs-file-writeallbytes – sioesi Oct 06 '16 at 13:52