Forums

Send files Fetch or ajax

I keep getting cross origin, or not found errors when I try to request a file from my Flask API. I can sent files to the uploads folder and edit the files but not send them back.

The below code is the simplified test.

from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from flask import send_from_directory
from werkzeug.utils import secure_filename
import os
import subprocess

app = Flask(__name__)

CORS(app)  # This will enable CORS for all routes

app.config['CORS_HEADERS'] = 'Content-Type'

UPLOAD_FOLDER = '/home/Bren3232/mysite/uploads'

@app.route('/get-file/<filename>', methods=['GET'])
@cross_origin()
def get_file(filename):

    f = open("print_log.txt", "a")
    f.write(f'UPLOAD_FOLDER is {UPLOAD_FOLDER}')
    f.write(f'filename var is {filename}')
    f.close()

    return send_from_directory(directory=UPLOAD_FOLDER, filename=filename, as_attachment=True)


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

[Edit by admin: formatting]

Do you want to add the site you're making requests from to the CORS_ORIGINS config? https://flask-cors.readthedocs.io/en/latest/configuration.html#configuration-options

Fixed. In newer versions of Flask they changed send_from_directory "filename" to "path".

Glad you got it working