Welcome folks today in this blog post we will be downloading files
from url as attachment in browser using filesaver.js
library in react.js and Javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
project using the below command
npx create-react-app sampleapp
npm i file-saver
And after that you need to copy paste the code inside the App.js
file as shown below
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import React from "react"; import { saveAs } from "file-saver"; export default function App() { const saveFile = () => { saveAs( "https://procodestore.com/wp-content/uploads/2021/03/164508084_271381191136191_654097929788476286_n.jpg", "example.pdf" ); }; return ( <div> <button onClick={saveFile}>download</button> </div> ); } |
As you can see we are importing the file-saver
library at the top and then we are having the button
to download the file
as an attachment from the url. We can also give the file a custom name.