简体   繁体   中英

How can I download a file from an API endpoint with a custom name?

I have a endpoint which gives me an URL for a like this:

https://api.com/v1/downs/IKw/9691.pdf

how can I download it?

I have a button, i am working with https://www.npmjs.com/package/file-saver :

import { save } from 'file-saver'
    const download = () => {
    const urlPdf = await givePdf()//is https://api.com/v1/downs/IKw/9691.pdf
    save(urlPdf)
    }
    <Button onClick={download}/>

the function givePdf only return a url as a string, that is ok i need download the file with a custom file, i tryed with this

saveAs(urlPdf, 'myPdf.pdf') but dont worked

I recommend using the download attribute to download a file instead of javascript:

<a href="https://api.com/v1/downloads/10/pv33oEokc0y7k-NY6EWIKw/label-52269691.pdf" download> Click here to download the pdf </a>

This will download your file without opening it.

You can do something like this:

const download = async () => {
   const urlPdf = await givePdf();
   window.open(urlPdf);
}

<Button onClick={download}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM