Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Download files using url in javascript

I have multiple url’s, pointing to different files. I want to be able to download them just by using the url string automatically with Javascript code, instead of manually going to the link and downloading them.

I have searched a lot of other answers on stackoverflow, few suggest creating an anchor tag in document body, but I am doing everything on backend not creating an index.html

edit: I am using next where for an api end point I am getting post requests, each which contains URL for a file which I have to download.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is how I expect my POST request to come:

enter image description here

I want to be able to do something like this (in nextjs):

export default async function handler (req, res) {
    if(req.method === "POST") {
       let path = "./downloads/file"
       await download(req.body.url, path)
    }
}

Is the download function possible, if so please help me with the implementation or provide any helpful packages to do the same.

>Solution :

You can HTTP client’s like Axios. It makes it easy to send async HTTP requests to REST endpoints and perform CRUD operations fairly easily, without you having write a lot of code.

You can refer to the snippet below that I have used in my previous projects for file downloads. I guess this is what you are looking for:

const fs = require('fs')  
const Path = require('path')  
const axios = require('axios')
const crypto = require('crypto')

async function downloadFile(url) {
    const uuid = crypto.randomUUID()

    const path = Path.resolve("./utils", "uploads", uuid)
    const writer = fs.createWriteStream(path)
    
    const response = await axios({
        url,
        method: 'GET',
        responseType: 'stream'
    })
    
    response.data.pipe(writer)

    return new Promise((resolve, reject) => {
        writer.on('error', reject)
        response.data.on('end', () => {
            resolve(uuid)
        })
    })
}

Hope this helps, and don’t forget to check out their documentation. Here is the
link.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading