Get a file name before saving it

泪湿孤枕 提交于 2019-12-13 03:24:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!