1

There is an API endpoint which offers a downloadable file - when accessing the url directly from the browser - the file is saved automatically. However, I would like to target the given endpoint from my app, and fetch the file name and content to a reducer within my app's redux store.

I'm using axios for all API requests. In this case, I'm trying to do it like this:

axios({
    url: API_ENDPOINT_URL,
    method: "GET",
    headers,
}).then((response) => {
    // do some stuff 
    console.log("response ", response)
})

In this setup, response contains only data, there is no filename. How to go about this?

idjuradj
  • 1,355
  • 6
  • 19
  • 31
  • so what does `response.data` contain? – Randy Casburn Jan 17 '19 at 21:52
  • "Browsers don't support downloading files through AJAX requests. You can check this stackoverflow.com/questions/32545632/… and also this https://stackoverflow.com/questions/35206589/how-to-download-fetch-response-in-react-as-file for more insight and some workarounds " from https://stackoverflow.com/questions/49832836/download-files-from-authorized-file-server-using-javascript-fetch-and-rest-api-e – MaieonBrix Jan 17 '19 at 21:53
  • See [Get a file name before saving it](https://stackoverflow.com/a/50642818/4642212). Is it in `response.data.headers`? – Sebastian Simon Jan 17 '19 at 21:55
  • 1
    @MaieonBrix - While your assumption about this use case is probably accurate, a little early to make that assessment. The OP may be looking at Byte (stream) data that can be used as a BLOB. – Randy Casburn Jan 17 '19 at 21:56
  • @RandyCasburn yes you are absolutely right, I did rush to answer. I am sorry – MaieonBrix Jan 17 '19 at 21:58
  • It's better done on a server side. – Alexander Kim May 18 '19 at 17:08

1 Answers1

-2

You can add a response type in axios that can be either stream or blob (depends on the file type)

axios({
  method:'get',
  url:'endpoint_url',
  responseType:'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('file_name.jpg'))
  })

This is straight from axios documentation. Let me know if you need something else

  • How does this get the file name? – Sebastian Simon Jan 17 '19 at 22:00
  • Hey Jacopo - I didn't downvote you, but your answer assumes NodeJS. The OP used the term 'reducer' which implies ReactJS operating in the browser. `fs` is not available in the browser. – Randy Casburn Jan 17 '19 at 22:01
  • Yes sure I get your point, the "problem" is that for the example above I test it on node, to be able to reassemble the file. The thing is that in the frontend part you can create a Blob instead of using fs – Jacopo Vendramin Jan 17 '19 at 22:16