Created
January 5, 2022 07:08
-
-
Save thesuhu/4f21d16c4b24c5f1d684f3d4423a7cf3 to your computer and use it in GitHub Desktop.
Axios Download File Stream and Write File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You can simply use response.data.pipe and fs.createWriteStream to pipe response to file | |
const axios = require('axios') | |
// Example 1: | |
axios({ | |
method: "get", | |
url: "https://xxx/my.pdf", | |
responseType: "stream" | |
}).then(function (response) { | |
response.data.pipe(fs.createWriteStream("/temp/my.pdf")) | |
}) | |
// Example 2: | |
axios.get('http://www.sclance.com/pngs/png-file-download/png_file_download_1057991.png', {responseType: "stream"} ) | |
.then(response => { | |
// Saving file to working directory | |
response.data.pipe(fs.createWriteStream("todays_picture.png")) | |
}) | |
.catch(error => { | |
console.log(error) | |
}) | |
// Example 3: | |
const FormData = require('form-data') | |
var data = new FormData() | |
data.append('file', fs.createReadStream('D:/temp/sample.pdf')) | |
var config = { | |
method: 'post', | |
url: 'https://xxx/api/sign/pdf?id=xxx&type=invisible&pass=xxx', | |
headers: { | |
'Authorization': 'Basic bmluamE6aGl0YW0=', | |
'Content-Type': 'application/json', | |
'Accept': 'application/pdf', | |
...data.getHeaders() | |
}, | |
responseType: 'stream', | |
data : data | |
} | |
response = await axios(config).then(response => { | |
response.data.pipe(fs.createWriteStream("D:/temp/sample_signed.pdf")) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment