2

I have one button in my react code and when I click it I should be able to download a file. I am using Python for backend(Not any framework). For react part I think this link explains what should be done. On button click, I should do an API call and on its return, I can render this IFrame component. Also, one other answer recommends responseType: 'blob' in axios call. My question is what should the backend do if we want to send a file over.Let's assume it just creates a file and returns it. I am actually using one third-party product which has its own API interface but an example with requests library would do.

def function_called_From_endpoint():
    with open(path) as f:
        return {'data': f }

Is something like this right?

Pratik
  • 1,351
  • 1
  • 20
  • 37
  • The code you posted will return a python dictionary object containing a python [file object](https://docs.python.org/3/glossary.html#term-file-object) Which probably Node cannot handle. Are you trying to return the contents of the file from the python function? – Alex Jul 10 '19 at 12:58
  • Yes I know returning file object won't work – Pratik Jul 10 '19 at 13:03
  • So what exactly are you trying to do? It seems to me you could just have the backend return a url to the file and have node get and download it. – Alex Jul 10 '19 at 13:05
  • @Alex I am trying to generate a file in backend and send it to UI on button click so that it can be be downloaded as attachment – Pratik Jul 11 '19 at 03:47

1 Answers1

1

So, I made it work this way:

def function_called_From_endpoint():
   with open(file_path) as f:
      data = f.read()

   return {"data": data }

and on the front-end:

  axios({
        url: url, //your url
        method: 'GET',
        responseType: 'blob', // important

  }).then((response) => {
         const url = window.URL.createObjectURL(new Blob([response.data]));
         const link = document.createElement('a');
         link.href = url;
         link.setAttribute('download', 'file.txt'); //or any other extension
         document.body.appendChild(link);
         link.click();
  });

As suggested by https://stackoverflow.com/a/53230807/5573241. It worked well.

Pratik
  • 1,351
  • 1
  • 20
  • 37