Get a File Name Before Saving It

I have a request that is supposed to download a file from remote api. What I want is, however, to save this file with the same name which it is saved with when I download the file from browser. For example, I have an URL , and when I click this link, browser immediately starts to download a file from that URL with name myfile20180601.txt. How do I save the file with the same name if I make a request from Node.js? This is my code:

axios({
    method: 'get',
    url: '
    responseType: 'stream',
    headers: {
        Authorization: 'Basic KJVEB46287blablablatoken'
    }
})
 .then(res => res.data.pipe(fs.createWriteStream(`${/* filename */}.txt`)))
 .catch(err => console.error(err));
2

3 Answers

You can find your filename in the response of axios

    var axios = require('axios')
    var fs = require('fs')

    axios({
        method:'get',
            url:'
            responseType:'stream'
        })
    .then(function(response) {
-       let headerLine = response.data.headers['content-disposition'];
+       let headerLine = response.headers['Content-Disposition'];
        let startFileNameIndex = headerLine.indexOf('"') + 1
        let endFileNameIndex = headerLine.lastIndexOf('"');
        let filename = headerLine.substring(startFileNameIndex, endFileNameIndex);
        response.data.pipe(fs.createWriteStream(filename));
    });

Hope this response helped you

I believe this will help!

let filename = response.headers['content-disposition'].split('filename=')[1].split('.')[0];
let extension = response.headers['content-disposition'].split('.')[1].split(';')[0];

console.log(`${filename}.${extension}`)

It has already been answered for backend, here i'm posting the answer for frontend.

You can get the browsed file name in by accessing the event --> event.target.files[0].name

Ex:

onChange={(event) => {
  const fileName = event.target.files[0].name;
  console.log('fileName', fileName);
}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest