[英]Allow user to download zip file generated on AWS
Here is how I do to generate ZIP and download it from a server, it works well in local development. 这是我生成ZIP并将其从服务器下载的方法,它在本地开发中效果很好。
import zipfile
doc = get_object_or_404(Document,id=id_obj)
filepath = doc.file.path
filename = os.path.basename(doc.file.name)
directory = os.path.dirname(filepath)
xzip = zipfile.ZipFile(os.path.join(directory,"%s.zip" % filename), "w")
xzip.write(filepath,filename)
xzip.close()
zip_file = open(xzip.filename, 'rb')
response = HttpResponse(zip_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s.zip"' %
os.path.splitext(filename)[0]
return response
All my static & media files are uploaded to AWS in production. 我所有的静态和媒体文件都已上载到AWS中。 So I change a little bit 所以我改变了一点
# filepath becomes
filepath = settings.MEDIA_ROOT + "/" + doc.file.name
But When I try to download it, it gives me [Errno 2] No such file or directory
with the link: 但是,当我尝试下载它时,它给了我[Errno 2] No such file or directory
链接:
https://bucket_name.s3.amazonaws.com/media/public/files/file.pdf.zip
the settings.MEDIA_ROOT
is: settings.MEDIA_ROOT
是:
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = 'bucket_name'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_PUBLIC_MEDIA_LOCATION = 'media/public'
MEDIA_ROOT = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_PUBLIC_MEDIA_LOCATION)
doc.file.path
gives me the error: 'This backend doesn't support absolute paths'
, that's why I changed to MEDIA_ROOT + doc.file.name
doc.file.path
给我错误: 'This backend doesn't support absolute paths'
doc.file.path
'This backend doesn't support absolute paths'
,这就是为什么我更改为MEDIA_ROOT + doc.file.name
How to do that to download from AWS the zip file generated? 如何从AWS下载生成的zip文件?
The file exists on S3, not the local file system. 该文件存在于S3上,而不是本地文件系统上。 When you call those os.path.*
functions the code is trying to find the file on the local file system. 当您调用这些os.path.*
函数时,代码将尝试在本地文件系统上查找文件。 It's giving you that error because that S3 URL you are giving it as the path can't be mapped to anything on the local file system. 这是给您的错误,因为您提供的S3 URL无法将路径映射到本地文件系统上的任何内容。
Why don't you allow S3 to serve the file directly to the end-user's browser by simply return a redirect response with the URL of the S3 file instead of trying to read the file and return the contents in the response? 为什么不通过仅返回带有S3文件URL的重定向响应而不是尝试读取文件并返回响应中的内容,而不允许S3将文件直接提供给最终用户的浏览器?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.