2

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; }); }; 

2 Answers 2

1

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"); }); }); 
Sign up to request clarification or add additional context in comments.

4 Comments

Can we download the images as well using this package?
Yes check you can Check out their Documentation
FileSaver.saveAs( "https://carbon-copiesrestapi.herokuapp.com/image_1628053278730.jpg", "histories.jpg"); It opened image in new tab rather than downloading.
read there docs carefully and see what they are saying
0

I resolved it by myself. This is how I resolved it.

  1. Installed package react-file-download.

  2. Imported it var fileDownload = require("react-file-download");

  3. 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" ); };

1 Comment

Unhandled Rejection (TypeError): Object(...) is not a function - imgur.com/d4GEGYo you could show all code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.