问题
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 https://myapi.com/files/4hjiguo4ho45946794526975429, 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: 'https://myapi.com/files/4hjiguo4ho45946794526975429',
responseType: 'stream',
headers: {
Authorization: 'Basic KJVEB46287blablablatoken'
}
})
.then(res => res.data.pipe(fs.createWriteStream(`${/* filename */}.txt`)))
.catch(err => console.error(err));
回答1:
You can find your filename in the response of axios
var axios = require('axios')
var fs = require('fs')
axios({
method:'get',
url:'https://myapi.com/files/4hjiguo4ho45946794526975429',
responseType:'stream'
})
.then(function(response) {
let headerLine = response.data.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
来源:https://stackoverflow.com/questions/50642065/get-a-file-name-before-saving-it