使用Boto下载S3文件 [英] Download S3 Files with Boto
问题描述
我正在尝试建立一个应用程序,用户可以在其中下载其存储在S3存储桶中的文件.我可以设置存储桶并获取正确的文件,但是无法下载,因此出现以下错误:没有这样的文件或目录:'media/user_1/imageName.jpg'
知道为什么吗?这似乎是一个相对容易的问题,但我似乎不太明白.我可以正确删除图像,以便能够识别正确的图像.
I am trying to set up an app where users can download their files stored in an S3 Bucket. I am able to set up my bucket, and get the correct file, but it won't download, giving me the this error: No such file or directory: 'media/user_1/imageName.jpg'
Any idea why? This seems like a relatively easy problem, but I can't quite seem to get it. I can delete an image properly, so it is able to identify the correct image.
这是我的观点.py
def download(request, project_id=None):
conn = S3Connection('AWS_BUCKET_KEY', 'AWS_SECRET_KEY')
b = Bucket(conn, 'BUCKET_NAME')
k = Key(b)
instance = get_object_or_404(Project, id=project_id)
k.key = 'media/'+str(instance.image)
k.get_contents_to_filename(str(k.key))
return redirect("/dashboard/")
推荐答案
问题是您正在下载到不存在的本地目录( media/user1
).您需要:
The problem is that you are downloading to a local directory that doesn't exist (media/user1
). You need to either:
- 首先在本地计算机上创建目录
- 只使用文件名而不是完整路径
- 使用完整路径,但将斜杠(
/
)替换为另一个字符-这将确保文件名的唯一性,而无需创建目录
- Create the directory on the local machine first
- Just use the filename rather than a full path
- Use the full path, but replace slashes (
/
) with another character -- this will ensure uniqueness of filename without having to create directories
最后一个选项可以通过以下方式实现:
The last option could be achieved via:
k.get_contents_to_filename(str(k.key).replace('/', '_'))
另请参阅: Boto3可以下载全部S3存储桶中的文件
这篇关于使用Boto下载S3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!