0

I am trying to download file using javascript. I am successfull in downloading the file using following code but when I Open the file the content is unreadble. I am not getting where am i going wrong. can anyone guide me on this to fetch the file with readable content ?

    function SaveToDisk(fileURL, fileName) {
        debugger;
        // for non-IE
        if (!window.ActiveXObject) {
            var save = document.createElement('a');
            save.href = fileURL;
            save.target = '_blank';
            save.download = fileName || 'unknown';

            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            });
            save.dispatchEvent(evt);

            (window.URL || window.webkitURL).revokeObjectURL(save.href);
        }

        // for IE < 11
        else if (!!window.ActiveXObject && document.execCommand) {
            var _window = window.open(fileURL, '_blank');
            _window.document.close();
            _window.document.execCommand('SaveAs', true, fileName || fileURL)
            _window.close();
        } 
}
Piyush Gupta
  • 2,181
  • 3
  • 13
  • 28
  • What's the content of `fileURL? Did you log this to console? – Johannes Jander Feb 17 '16 at 10:00
  • you can refer this http://jsfiddle.net/a856P/51/ – Piyush Gupta Feb 17 '16 at 10:01
  • i am trying with a simple "txt" file which has some text in it. so my fileUrl ="/Documentation/mutualfundforms/" and filename = "get.txt" but after the file gets downloaded its in unreadable format @PiyushGupta – user3682373 Feb 17 '16 at 10:07
  • i am trying with a simple "txt" file which has some text in it. so my fileUrl ="/Documentation/mutualfundforms/" and filename = "get.txt" but after the file gets downloaded its in unreadable formaT @JohannesJander – user3682373 Feb 17 '16 at 10:14
  • Can you set this up in a fiddle or JSBin? Typically, for file downloads from JS, you need to build a blob and use a data: url. – Johannes Jander Feb 17 '16 at 10:18
  • 1
    possible duplicate of [Download File Using Javascript/jQuery](http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery) – PHPExpert Feb 17 '16 at 10:34
  • 1
    Update that code also where you are calling SaveToDisk function because i tried this is working for me http://jsfiddle.net/Ezx5m/73/ – Piyush Gupta Feb 17 '16 at 10:37
  • Hey @PiyushGupta your solution worked for me. Thanks a tone – user3682373 Feb 18 '16 at 05:36
  • how can i put a validation of checking the file existence first and then download it ? @PiyushGupta – user3682373 Feb 18 '16 at 05:38
  • refer this http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascript?answertab=oldest#tab-top – Piyush Gupta Feb 18 '16 at 05:44

0 Answers0