保存之前获取文件名 [英] Get a file name before saving it
问题描述
我有一个应该从远程api下载文件的请求.但是,我想要的是使用与从浏览器下载文件时保存的名称相同的名称保存该文件.例如,我有一个URL https://myapi.com/files/4hjiguo4ho45946794526975429
,当我单击此链接时,浏览器立即开始从该URL下载名称为myfile20180601.txt
的文件.如果我从Node.js发出请求,如何用相同的名称保存文件?这是我的代码:
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));
推荐答案
您可以在axios的响应中找到文件名
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))
});
希望此回复对您有帮助
这篇关于保存之前获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!