I am in the process of creating a web application that utilizes HTML along with plain Javascript for the frontend, and Flask as the backend. The main function of the application is to send an ID to the server, where it will then generate a PDF report and send it back to the client.
In order to achieve this, I have set up an endpoint using Flask:
@app.route("/download_pdf", methods=['POST'])
def download_pdf():
if request.method == 'POST':
report_id = request.form['reportid']
print(report_id) //For testing purposes.
// Perform necessary operations with report_id to generate a PDF file.
return send_file('/home/user/report.pdf', mimetype='application/pdf', as_attachment=True)
// Various attempts were made with different values for mimetype and as_attachment=False
Testing the endpoint from the command line results in obtaining the correct file, with the server console displaying the expected report ID (123):
curl --form reportid=123 http://localhost:5000/download_pdf >> output.pdf
On the frontend side, I have created a button that triggers a JavaScript function:
<button id=pdf_button onclick="generatePdf()"> PDF </button>
The JavaScript function is structured as follows:
function generatePdf(){
var report_list = document.getElementById("report_list")
if (report_list.selectedIndex < 0){
alert("Please select a report.");
}else{
var req = new XMLHttpRequest();
req.open("POST", "/download_pdf", true);
req.responseType = "document";
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.onreadystatechange = function(){
console.log(req.readyState)
console.log(req.status)
console.log(req.response)
var link = document.createElement('a')
link.href = req.response;
link.download="report.pdf"
link.click()
}
var selected_value = report_list.options[report_list.selectedIndex].value;
var params="reportid="+selected_value;
req.send(params);
}
};
In this case, req.response returns null. Nevertheless, the call to the endpoint is executed correctly, as evidenced by the backend console displaying the report ID as intended.
Attempts made so far include:
- Setting responseType to "blob" and "arraybuffer" based on this resource.
- Verifying the HTTP return code, which consistently shows 0.
- Replacing req.onreadystatechange with req.onload, but no output is observed in the console.
Furthermore, upon clicking the button, the Firefox console displays 6 messages (make sure to observe the console.log() calls in the preceding code):
2
0
null
4
0
null
It appears that the JavaScript function is being called twice when the button is pressed.
My objective is to successfully download the PDF. Any assistance or guidance would be greatly appreciated as I attempt to resolve this issue.