The simple implementation to upload a file using ajax to wcf rest service is explained as:-
- 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; }
- 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);
- 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>
- 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); "
No comments:
Post a Comment