--- title: Vue.js 使用 axios + flask 下載檔案 tags: Vue.js, flask description: Vue.js 使用 axios + flask 下載檔案 --- # Vue.js 使用 axios + flask 下載檔案 前端使用v-on綁定Buttin監聽事件,click後觸發透過axios下載後端數據。 ## 前端環境 Vue.js + axios ``` <template> <div> <button @click="'"onClick()">DownLoad</button> </div> </template> <script> import axios from 'axios' export default { methods: { onClick() { axios({ url: 'http://localhost:5000/download', method: 'GET', responseType: 'blob', }).then((response) => { var fileURL = window.URL.createObjectURL(new Blob([response.data])); var fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', 'read.txt'); document.body.appendChild(fileLink); fileLink.click(); }); } } } </script> <style> </style> ``` --- ## 後端環境 python3 + flask ``` from flask import Flask, request, send_from_directory from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/download', methods=["GET", "POST"]) root_path = '/home/' src_name = "read.txt" upload_path = os.path.join(root_path, src_name) if os.path.isfile(upload_path): response = send_from_directory(root_path, src_name, as_attachment=True) response.headers["Access-Control-Expose-Headers"] = "Content-disposition" return response if __name__ == "__main__": app.run(host="0.0.0.0", port="5000", debug=True) ``` --- ## Thank you! :dash: You can find me on - GitHub: https://github.com/shaung08 - Email: a2369875@gmail.com