flask_restful實現文件下載功能


環境:前后端完全分離,后端flask_restful,前端vue

from flask_restful import reqparse, Resource
from flask import send_from_directory,send_file,safe_join
from werkzeug.utils import secure_filename

class DownloadTemplates(Resource):
    def get(self):
        parser = reqparse.RequestParser(trim=True)
        parser.add_argument('filename', required=True, nullable=False, location=['args'])
        args = parser.parse_args()
        filename = args['filename']
        path = handle_manage.template_dir
        response = send_from_directory(path, filename, as_attachment=True)
        return response


注意:這種做法有時會報錯404,提示找不到url
genericpath.py 如果系統安裝了這個組件的話:
 
會替換系統自帶的path功能,導致,path失效了。最終會找不到文件。
 
代碼只有這樣簡短的幾句話而已。就是這個os.path.isfile會有問題。所以,放在uploaded_file中來完成這個動作,就可以了

class DownloadTemplates(Resource):
    def get(self):
        parser = reqparse.RequestParser(trim=True)
        parser.add_argument('filename', required=True, nullable=False, location=['args'])
        args = parser.parse_args()
        UPLOAD_FOLDERS = handle_manage.template_dir
        filename = args['filename']
        return send_file(safe_join(UPLOAD_FOLDERS, secure_filename(filename)), as_attachment=True)

 

 

前端

this.currentNode.path 為文件絕對路徑
//方法一
//response.data + '/' + download_url 是絕對地址
window.open(response.data + '/' + download_url, '_blank');
//方法二
let a = document.createElement('a')
a.href = response.data + '/' + download_url
a.click();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM