PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How do I write inta a file and download the file using Javascript?

 September 08, 2022     ajax, download, get, javascript     No comments   

Issue

A file is getting uploaded to a remote server and I need to download the file to the local machine. Im running a GET call through ajax to get the data. On running the following code -

      console.log(xhrdoc.responseText);

This line returns the contents of the file in the console in the browser. I need to write this data into a file and then download the file using Javascript. The file can be in any format like txt, pdf, png,jpg etc. Is there also a way to handle all different file formats in one way? My first priority though is txt file. How can i do that?

Any help would be appreciated. Thank you.


Solution

Ideally you can do this simply by using data URIs. Creating a <a> tag and providing a blob into href attribute of the tag.

<a href="data:application/octet-stream;charset=utf-16le;base64,//VGV4dCBmaW5sZSBleGFtcGxl">Link to download text file</a>

But if you want it to be downloaded by a script, you can create an <a> tag and click on it programatically and delete the <a> tag.

Please try the below code in browser console. As the Run code snippet button seems to not work for some reason.

function downloadFileWithContents(filename, fileContents) {
  const blob = new Blob([fileContents], {type: 'text'}); // create a blob with fileContents
  if(window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveBlob(blob, filename);
  }
  else{
      const elem = window.document.createElement('a');
      elem.href = window.URL.createObjectURL(blob);
      elem.download = filename;        
      document.body.appendChild(elem);
      elem.click();        
      document.body.removeChild(elem);
  }
}

downloadFileWithContents('Filename.txt', 'TEXT');
// downloadFileWithContents('Filename.txt', xhrdoc.responseText)



Answered By - LEXTRA33
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing