Home > Blockchain >  How to download any file from the content i receive in the response
How to download any file from the content i receive in the response

Time:12-14

{ "title": "Dummy File", "name": "temp_file.csv", "content": "name,role\r\n" } I have to download in file in the frontend using the above content in react. How to do it?

CodePudding user response:

could just use native js based on this example

// some api response
const fileContent = { "title": "Dummy File", "name": "temp_file.csv", "content": "name,role\r\n" }

// implementation
const link = document.createElement('a');
link.download = fileContent.name;
link.href = 'data:text/csv;charset=utf-8,'   encodeURI(fileContent.content);
link.click();

This also assumes that file extension will always be CSV.

react example:

import React from 'react';

export function App(props) {

  const fileContent = { "title": "Dummy File", "name": "temp_file.csv", "content": "name,role\r\n" }

function downloadFile() {
  const link = document.createElement('a');
  link.download = fileContent.name;
  link.href = 'data:text/csv;charset=utf-8,'   encodeURI(fileContent.content);
  link.click();
}

  return (
    <button onClick={downloadFile}>Download File</button>
  );
}
  • Related