Download Image From Image URL In Windows 10 Universal App Using WinJS and JavaScript

Universal Windows Platform provides the common application platform and lets developers build apps using JavaScript/HTML, C#/XAML and C++, etc. As we all know the WinJS library helps us build Windows 10 universal Apps in HTML5 and JavaScript. The WinJS.xhr in WinJS helps wrap cross-domain calls and provides an easy mechanism to work with external web contents using HTTP operations like POST/ GET etc.

Let’s see the steps.

Create new windows 10 universal appp using WinJS. For creating a new Windows 10 universal project, refer to the following:

Now go to your default.html page and write the following code inside the body tag.

  1. <table style="width: 100%;border:double">  
  2. <tr>  
  3. <td> Enter Url Here  
  4. <td>  
  5. </tr>  
  6. <tr>  
  7. <td> <input id="txturl" type="text" style="width:800px" /> </td>  
  8. <td> <input id="btngetfile" type="button" value="Download" /> </td>  
  9. </tr>  
  10. <tr>  
  11. <td> </td>  
  12. <td> </td>  
  13. <td> </td>  
  14. </tr>  
  15. <tr>  
  16. <td align="center">  
  17. <div id="dvcontainer"> </div>  
  18. </td>  
  19. </tr>  
  20. </table>  
Here, I create one textbox to get the URL from the user, one button to perform the download operation and one div to show the downloaded image.

Now go to your default.js file present under js folder in the solution files and write the following code inside the function tag to perform the download button click event.
  1. var page = WinJS.UI.Pages.define("default.html",  
  2.        {  
  3.            ready:function(element,options)  
  4.            {  
  5.                document.getElementById("btngetfile").addEventListener("click", downloadFile, false);  
  6.            },  
  7.        });  
  8.     function downloadFile() {  
  9.         var url = document.getElementById('txturl').value;  
  10.         WinJS.xhr({ url: url, responseType: "blob" })  
  11.         .done(function (r) {  
  12.             var fileURL = URL.createObjectURL(r.response);  
  13.             var image = dvcontainer.appendChild(document.createElement("img"));  
  14.             image.src = fileURL;  
  15.   
  16.         });  
  17.     }  
Here I pass the image URL and define the response type as blob to download the image in WinJS xhr method. Once the file is downloaded append the image inside the div which is already we created dvcontainer.

Now run the app and enter your image URL into the textbox and click download button it will show the output like the following screen.

output

For more information on Windows 10 UWP, refer to my e-book:
Read more articles on Universal Windows Platform:


Similar Articles