如何在Django中从AWS S3读取文件并发送给用户?
从AWS S3读取文件并实现Django下载功能
原视图函数通过读取本地文件实现下载,但文件实际存储在AWS S3存储桶中,需要调整代码直接从S3获取文件内容并返回给用户,以下是修改方案:
前置准备
- 安装AWS SDK for Python:
pip install boto3 - 配置AWS凭证:通过环境变量、
~/.aws/credentials文件或Django配置文件设置AWS_ACCESS_KEY_ID和AWS_SECRET_ACCESS_KEY,确保账号拥有目标S3存储桶的读取权限。
修改后的Download视图函数
import boto3 from django.http import HttpResponse from django.views import View from django.shortcuts import render import os from your_app.models import KarafetaProduct # 替换为实际的模型路径 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class Download(View): def get(self, request): # 保留原模板路径处理逻辑 try: if request.session["language"] == "en": the_path_of_templates = "website/en/" else: the_path_of_templates = "website/ar/" except: the_path_of_templates = "website/en/" try: the_file = KarafetaProduct.objects.all()[0] s3_bucket_name = "karafeta-bucket" # 若模型中存储了S3文件键,可替换为the_file.s3_key等字段值 s3_file_key = "Python-3.11.5_3_q9ZN0gC.exe" # 初始化S3客户端 s3 = boto3.client('s3') # 从S3读取文件二进制内容 s3_response = s3.get_object(Bucket=s3_bucket_name, Key=s3_file_key) file_data = s3_response['Body'].read() # 构建下载响应 response = HttpResponse(file_data, content_type='application/vnd.microsoft.portable-executable') response['Content-Disposition'] = f'attachment; filename="{the_file.name}"' return response except Exception as e: # 可选:添加日志记录异常信息便于排查 # import logging; logging.error(f"下载失败: {str(e)}") return render(request=request, template_name=f"{the_path_of_templates}home.html")
关键说明
- S3客户端初始化:
boto3.client('s3')会自动读取配置的AWS凭证信息,无需手动传入。 - 文件读取逻辑:通过
get_object方法指定存储桶名和文件键(S3中文件的唯一标识),从响应体中读取二进制内容。 - 响应头配置:保留原有的
Content-Type和Content-Disposition设置,确保浏览器识别为可下载附件。 - 异常处理:保留原错误跳转逻辑,建议添加日志记录S3访问失败、文件不存在等异常场景。
内容的提问来源于stack exchange,提问作者Mohammed almalki
相关产品推荐
相关产品推荐

