TIL
flask 파일 다운로드하기 (send_file, Content-Disposition)
kimbro6
2022. 10. 29. 08:23
#1 서론
프로젝트를 진행하면서 사용자가 어떤 파일을 다운로드 받게 하는 기능을 구현했다.
위의 내용을 정리하여 글을 쓴다.
#2 본론
#2-1 저장되어있는 파일을 다운로드
파일을 다운로드 시키려면 아래의 코드를 쓰면 된다.
send_file([file_route], mimetype=[mimetype], as_attachment=True)
[] 안에 들어가는 것들을 알아서 넣고, 예시와 비슷한 코드를 만들어서 실행하면 된다.
#예시
from flask import send_file
@app.route("/download")
def download_test():
retrun send_file("download_files/test.text", mimetype="text/plain", as_attachment=True)
#2-2 저장하지않고 직접생성한 데이터 다운로드
데이터를 Response객체에 넣고, mimetype을 정해준다음 response.headr["Content-Disposition"]에 attachment설정을 해주면 된다. 추가로 다운로드되는 이름을 filename 에 저장해주면 된다.
예시)
@app.route("/download_file")
def download_file():
response = Response("이건 이제 다운로드 될겁니다", mimetype='text/plain')
response.headers["Content-Disposition"] = f"attachment; filename={file_name}"
return response
#3 결론
아래의 블로그 덕분에 문제와 글을 쉽게 쓸 수 있었다.
#4 참고자료
https://frhyme.github.io/python-libs/file_download_with_flask/