0

TL;DR: Please let me know how to download the data as a file and trigger a browser file download action.

I am building a React + Rails API application that generates a "report.xls" file and should download it to the browser when a GET request is made using the api. Here is the axios file that is making the request on the front-end:

import axios from 'axios';

const fetchReport = () => axios.get("/generate_report");

In my rails routes.rb, I have a route defined like this:

get "/generate_report", to: "attempts#generate_report"

And finally in my attempts_controller.rb file, the generate_report function is defined like this:

def generate_report
    data = CSV.generate(col_sep: "\t") do |csv|
        csv << ["Quiz Name", "User Name", "Email", "Correct Answers", "Incorrect Answers"]
        @current_user.quizzes.each do |quiz|
            quiz.attempts.each do |attempt|
                if attempt.submitted == true
                    csv << [attempt.quiz.title, attempt.user.full_name, attempt.user.email, attempt.correct_answers_count, attempt.incorrect_answers_count]
                end
            end
        end
    end

    send_data data, type: "application/vnd.ms-excel", filename: "report.xls", disposition: "attachment"
end

So, instead of a .xls file being downloaded, I am receiving file data in the response:

"Quiz Name\tUser Name\tEmail\tCorrect Answers\tIncorrect Answers\nSecond Quiz\tRed White\tr@w.com\t2\t0\nFirst Quiz\ta t\ta@t.com\t2\t1\nFirst Quiz\tq s\tq@s.com\t3\t0\nFirst Quiz\tx y\tx@y.com\t3\t0\nFirst Quiz\tz x\tz@x.com\t1\t2\nFirst Quiz\tninja hatori\tninja@hatori.com\t1\t2\nFirst Quiz\tfairst last\tfirst@last.com\t3\t0\nFirst Quiz\tRay Ban\tray@bna.com\t2\t1\nFirst Quiz\ta b\ta@b1.com\t3\t0\nFirst Quiz\ta b\ta@b.com\t2\t1\n"

Here is the complete response:

{
    "data": "Quiz Name\tUser Name\tEmail\tCorrect Answers\tIncorrect Answers\nSecond Quiz\tRed White\tr@w.com\t2\t0\nFirst Quiz\ta t\ta@t.com\t2\t1\nFirst Quiz\tq s\tq@s.com\t3\t0\nFirst Quiz\tx y\tx@y.com\t3\t0\nFirst Quiz\tz x\tz@x.com\t1\t2\nFirst Quiz\tninja hatori\tninja@hatori.com\t1\t2\nFirst Quiz\tfairst last\tfirst@last.com\t3\t0\nFirst Quiz\tRay Ban\tray@bna.com\t2\t1\nFirst Quiz\ta b\ta@b1.com\t3\t0\nFirst Quiz\ta b\ta@b.com\t2\t1\n",
    "status": 200,
    "statusText": "OK",
    "headers": {
        "cache-control": "no-store, must-revalidate, private, max-age=0",
        "content-disposition": "attachment",
        "content-transfer-encoding": "binary",
        "content-type": "application/vnd.ms-excel",
        "referrer-policy": "strict-origin-when-cross-origin",
        "transfer-encoding": "chunked",
        "vary": "Origin",
        "x-content-type-options": "nosniff",
        "x-download-options": "noopen",
        "x-frame-options": "SAMEORIGIN",
        "x-miniprofiler-ids": "ejkccxx23nsh2fqfx2i2,h89r6g5jivum9mcbzr8x,97dg82u8dgzczupteuqz,9ss0wogrwb1ojcjyshei",
        "x-miniprofiler-original-cache-control": "private",
        "x-permitted-cross-domain-policies": "none",
        "x-request-id": "98dd6f11-44ca-4333-b8a3-f2b01771be82",
        "x-runtime": "10.071530",
        "x-xss-protection": "1; mode=block"
    },
    "config": {
        "url": "/generate_report",
        "method": "get",
        "headers": {
            "Accept": "application/json",
            "X-CSRF-TOKEN": "VcALUh9gr3qEqEMMN2LNLxY8Q1umTCNCXEbGMr59k_ayUBGfr4VSbd7vY6POQSuHsKPaP3OeCXFqqmWn9KRbIQ"
        },
        "baseURL": "/",
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        }
    },
    "request": {},
    "success": true
}

I tried the same with send_file file.path but there too, instead of receiving the file, I am getting base64 data of the file in response. Please let me know how to download the data as a file and trigger a browser file download action.

Karan Sapolia
  • 482
  • 8
  • 15
  • This should help someone with a similar problem: https://stackoverflow.com/questions/29319433/using-ajax-to-download-a-file. I got it working following this question, but I'd still appreciate a complete answer. – Karan Sapolia Oct 03 '21 at 14:11

0 Answers0