Skip to content

Instantly share code, notes, and snippets.

@thesuhu
Created January 5, 2022 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thesuhu/4f21d16c4b24c5f1d684f3d4423a7cf3 to your computer and use it in GitHub Desktop.
Save thesuhu/4f21d16c4b24c5f1d684f3d4423a7cf3 to your computer and use it in GitHub Desktop.
Axios Download File Stream and Write File
// 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