问题
I want to create an admin action to download users pdf files The user file would be uploaded in the media directory What and the admin should be able to download any file I tried using pdfkit to let him download the files but I couldn't
> import pdfkit
>
> def downloadCV(self, request, queryset):
> projectUrl = str(queryset[0].cv)+''
> pdf = pdfkit.from_url(projectUrl, False)
> response = HttpResponse(pdf,content_type='application/pdf')
> response['Content-Disposition'] = 'attachment; filename="user_cv.pdf"'
So my question is what is the best way to let the admin dowload pdf files
I tried this way
def downloadCV(self, request, queryset):
for x in queryset:
projectUrl = str(x.cv)+''
if projectUrl:
with open(projectUrl, 'r') as pdf:
response = HttpResponse(pdf,content_type='application/pdf')
response['ContentDisposition']='attachment;filename="user_cv.pdf"'
return response
pdf.closed
but I can only download one file at atime is there is away to download multiples pdfs at once ?
回答1:
A request can only give one response. So i think you have 2 options
Option 1, You could make multiple requests. Basically similar to the code you have now but targeting one file but with some kind of javascript code that will run the action on an individual file in a new tab/window. So say you checked off 3 files in the admin and ran the action it would need to open 3 tabs each one its own file serving you the pdf.
Option 2, Zip up the files and return that one zip file instead. This seems easier to me. Here is an example that I haven't tested but you get the idea.. gather the files together from the queryset then shove them in a zipfile and then serve up the zipfile.
import pdfkit
import tempfile
import zipfile
def downloadCV(self, request, queryset):
with tempfile.SpooledTemporaryFile() as tmp:
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive:
for index, item in enumerate(queryset):
projectUrl = str(item.cv) + ''
fileNameInZip = '%s.zip' % index
pdf = pdfkit.from_url(projectUrl, False)
archive.writestr(fileNameInZip, pdf)
tmp.seek(0)
response = HttpResponse(tmp.read(), mimetype='application/x-zip-compressed')
response['Content-Disposition'] = 'attachment; filename="pdfs.zip"'
return response
来源:https://stackoverflow.com/questions/42077645/how-to-make-an-admin-action-in-django-to-download-users-pdf-files