最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

http - Download files using url in javascript - Stack Overflow

programmeradmin0浏览0评论

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.

This is how I expect my POST request to e:

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.

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.

This is how I expect my POST request to e:

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.

Share Improve this question asked Jul 22, 2022 at 10:25 venkata avinash appalavenkata avinash appala 1011 gold badge1 silver badge5 bronze badges 5
  • It isn't really clear what you are trying to acheive here. Is the flow supposed to go: The client (e.g. browser or postman) on puter A makes an HTTP request to your Next.js API running on puter B which makes an HTTP request to another API to get a URL which puter B then uses to make another HTTP request to that URL which responds with a file that puter B saves to puter B's hard disk and then sends an HTTP response to puter A saying it was successful? – Quentin Commented Jul 22, 2022 at 10:31
  • @Quentin Computer A sends a url via a post request to the API running on Computer B, I want to be able to download the file at the location pointed by the url and save it in puter B. I guess the answer mentioning the use of axios below solves my query. – venkata avinash appala Commented Jul 22, 2022 at 10:40
  • Duplicate: stackoverflow./questions/11944932/… – Quentin Commented Jul 22, 2022 at 10:42
  • Duplicate: stackoverflow./questions/51444927/… – Quentin Commented Jul 22, 2022 at 10:42
  • Duplicate: stackoverflow./questions/58642368/… – Quentin Commented Jul 22, 2022 at 10:43
Add a ment  | 

2 Answers 2

Reset to default 4

You can use HTTP clients like Axios. It makes it easy to send async HTTP requests to REST endpoints and perform CRUD operations.

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.

Download by get request

const downloadFabricFormat = async () => {
    try{
      await axios({
        url: '/api/fabric/fabric_excel_format/',
        method: 'GET',
        responseType: 'blob',
      }).then((response) => {
         const url = window.URL.createObjectURL(new Blob([response.data]));
         const link = document.createElement('a');
         link.href = url;
         link.setAttribute('download', 'Fabric Excel Format.xlsx');
         document.body.appendChild(link);
         link.click();
      });
    } catch(error){
      console.log(error)
    }
  };

Download by post request

  const postFabricQRCode = async (values) => {
    try{
      await axios({
        url: `/api/qr/code/download/`,
        method: 'POST',
        responseType: 'blob',
        data: values,
      }).then((response) => {
         const url = window.URL.createObjectURL(new Blob([response.data]));
         const link = document.createElement('a');
         link.href = url;
         link.setAttribute('download', 'fabric-qr-code.pdf');
         document.body.appendChild(link);
         link.click();
      });
    } catch(error){
      console.log(error)
    }
  };

Change file type here. link.setAttribute('download', 'Fabric Excel Format.xlsx'); Also manage your back-end yourself.

发布评论

评论列表(0)

  1. 暂无评论