1

I am trying to download xlsx file. I post an id and using it to get data from database. Then i can create an excel file but i couldn't download it.

My backend codes:

from flask import Flask
from flask import request, jsonify, make_response, json, send_file, redirect, url_for,send_from_directory
from bson.json_util import dumps
from flask_cors import CORS
import dbConnections.Test as db
import os

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}}, support_credentials=True)


@app.route("/test-report", methods=["POST"])
def downloadTestReport():
    req = request.get_json();
    results = db.GetTestResult(req)
    return send_file('foo.xlsx', as_attachment=True)

if __name__ =="__main__":
    app.run(debug=True)

And my frontend codes:

    let downloadReport = (e)=>{
        if(e.field ==="downloadReport"){
            const objId=  {testId: e.row.objId};
            
            axios.post('http://127.0.0.1:5000/test-report', objId)
            .then(function (response) { 
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });       
        }
    }

The result on my console: enter image description here

I wanna download excel file which is return.

Burak Algur
  • 326
  • 1
  • 2
  • 10

1 Answers1

1

To show what Ethan's comment is in code, Assuming your backend flask code is sending the Excel file as it should, your frontend code should look like this:

                axios('/test-report', {
                    method: 'GET', //Pretty sure you want a GET method but otherwise POST methods can still return something too.
                    responseType: 'blob', // important
                }).then((response) => { //Creates an <a> tag hyperlink that links the excel sheet Blob object to a url for downloading.
                    const url = window.URL.createObjectURL(new Blob([response.data]));
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', `${Date.now()}.xlsx`); //set the attribute of the <a> link tag to be downloadable when clicked and name the sheet based on the date and time right now.
                    document.body.appendChild(link);
                    link.click(); //programmatically click the link so the user doesn't have to
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url); //important for optimization and preventing memory leak even though link element has already been removed. In the case of long running apps that haven't been reloaded many times.    
                });

This is in reference to:

//https://stackoverflow.com/questions/41938718/how-to-download-files-using-axios?noredirect=1&lq=1

How to download excel in response from api react.js