Reputation: 63
I have this link https://carbon-copies-restapi.herokuapp.com/all-order-histories.txt which contains some data. I want to download it as a file using React. I tried many solutions from StackOverflow but nothing worked for me. One of the solutions I found on the internet that did not work either.
const downloadFile = async () => {
fetch(
"https://carbon-copies-restapi.herokuapp.com/all-order-histories.txt"
).then((response) => {
response.blob().then((blob) => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement("a");
a.href = url;
a.download = "orders.txt";
a.click();
});
//window.location.href = response.url;
});
};
Upvotes: 2
Views: 18197
Reputation: 1329
Checkout Filesaver.js for downloading Small Files and for Big file and more control use StramSaver.js
Using FileSaver JS
FileSaver.saveAs("https://carbon-copies-restapi.herokuapp.com/all-order-histories.txt", "histories.txt");
Other Methods using FileSaver JS
const downloadFile = async () => {
fetch("https://carbon-copies-restapi.herokuapp.com/all-order-histories.txt").then((response) => {
response.blob().then((blob) => {
var FileSaver = require('file-saver');
var blob = new Blob(blob, {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");
});
});
Upvotes: 1
Reputation: 63
I resolved it by myself. This is how I resolved it.
Installed package react-file-download.
Imported it var fileDownload = require("react-file-download");
I was getting all the data from backend in this object allOrders.data.rentalHistories. Stringify it and stored it in file name allOrders.txt and invoked the function on button click. But this approach is only useful if you are getting this data from backend
const downloadFile = () => { fileDownload( JSON.stringify(allOrders.data.rentalHistories), "allOrders.txt" ); };
Upvotes: 0