Uploading file using ajax and wcf rest

The simple implementation to upload a file using ajax to wcf rest service is explained as:-

1. Create the wcf rest service as :-
    
public JsonResponse<string> SaveImage(Stream imageFile)
{
         JsonResponse<string> response = new JsonResponse<string>();
         String filePath = @"D:\abcd.jpg";
        using (FileStream writer = new FileStream(filePath , FileMode.Create))
         {
                int readCount;
                var buffer = new byte[4096];
                while ((readCount = imageFile.Read(buffer, 0, buffer.Length)) > 0)
                {
                    writer.Write(buffer, 0, readCount);
                }
         }
         response.IsSuccess = true;

return response;
}

2. Set the operation contract as:- 

   [OperationContract]
   [WebInvoke(Method = "POST",
                     UriTemplate = "/SaveImage",
                     BodyStyle =    WebMessageBodyStyle.WrappedRequest,
                     ResponseFormat = WebMessageFormat.Json,
                     RequestFormat = WebMessageFormat.Json,)]
  JsonResponse<string> SaveImage(Stream imageFile);

3. Create the javascript method for uploading the file :-

   <script>
   function UploadFile() {
        var result;
        var fileData = document.getElementById("userImage").files[0];
        var xhr = new XMLHttpRequest();
        var serviceURL = "http://192.168.1.8:8086/wcfService.svc/SaveImage";

        xhr.onreadystatechange = function (Evt) {
            if (xhr.readyState == 4 && xhr.status == 200) {
                   Data = JSON.parse(xhr.responseText);
                   result = Data.IsSuccess;
                   if (result == true) {
                         alert('Image uploaded successfully');
                    }
                  
               }
            }
        };

        xhr.open('POST', serviceURL, true);

        xhr.send(fileData);
    }
    </script>

4. write the HTML for input control and button as :-

<input id="userImage" type="file" name="flupProfile" accept="image/*"/>
<button onclick="UploadFile()">Upload</button >

The above function will send the request asynchronously. We can also send a synchronous request by setting the third parameter in xhr.Open to false i.e. using " xhr.open('POST', serviceURL, false); " instead of " xhr.open('POST', serviceURL, true); "

NOTE : If you get error for  "No 'Access-Control-Allow-Origin' header is present on the requested resource.", then try adding CORS handling to your site, if you still see this error then you might have to change localhost to some domain name or you have to run it through server. For more information refer the link

No comments:

Post a Comment