-
flask 파일 다운로드하기 (send_file, Content-Disposition)TIL 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/
'TIL' 카테고리의 다른 글
리처드 파인만 공부방법, 암기 잘하는 방법 (0) 2023.09.08 20221109_TIL : flask, request의 정보 받아오는 방법(get메서드) (0) 2022.11.09 20221028_TIL : git 변경 또는 삭제된 파일 add 방법 (0) 2022.10.28 20221027_TIL : flask 디버그 모드 실행 방법 (0) 2022.10.27 20221026_TIL : .gitignore 사용하여 commit하고 싶지 않은 파일 배제하기 (0) 2022.10.26