.pdf在存储和下载后已损坏

时间:2018-11-05 18:50:57

标签: python django django-storage

我已经将.pdf存储在models.FileField中,并使其可供用户下载。但是当我下载文件时,它已损坏。谁能告诉我是否正确地存储它或将我指向某个方向?我的设置如下:

models.py

class Barcard(models.Model):
    name = models.CharField(max_length=30)
    drinks = models.ManyToManyField(Drink)
    barcardFile = models.FileField(blank=True, upload_to='barcard') 
    mixingFile = models.FileField(blank=True, upload_to='mixing') 

    def generateFiles(self):
        bashCommand = 'make -C tkweb/apps/drinks/drinkskort/'
        subprocess.call(bashCommand, shell=True)
        barFile = open('tkweb/apps/drinks/drinkskort/bar_drinks.pdf', encoding = "ISO-8859-1")
        mixFile = open('tkweb/apps/drinks/drinkskort/mixing_drinks.pdf', encoding = "ISO-8859-1")
        self.barcardFile.save(self.name+'_barcard',File(barFile))
        self.mixingFile.save(self.name+'_mixing',File(mixFile))

view.py

def barcardGen(request):
    if request.method =='POST':
        card = request.POST.get('barcard')
        card_obj = Barcard.objects.get(id=card)
        barcardName = card_obj.name
        card_obj.generateFiles()
        return HttpResponseRedirect('/drinks/download/'+card)
    else:
        return HttpResponseRedirect('/drinks/')

def download(request, barcard_id):
    if request.method == 'GET':
        barcard = get_object_or_404(Barcard, pk=barcard_id)
        return render(request, 'drinks/download.html', {'barcard':barcard})
    else:
        return HttpResponseRedirect('/drinks/')

template / drinks / download.py

{% extends "drinks/base.html" %}
{% block fulltitle %}Drinks{% endblock %}
{% block content %}
<h1>{{ barcard.name }}</h1>
<p> Download barkort her: <a href='{{barcard.barcardFile.url}}'>{{barcard.name}} barkort</a> </p>
<p> Download blandekort her: <a href='{{barcard.mixingFile.url}}'>{{barcard.name}} blandeliste</a></p>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

PDF文件是二进制文件。您应该使用二进制模式rb来阅读它们,而不指定文本编码:

barFile = open('tkweb/apps/drinks/drinkskort/bar_drinks.pdf', "rb")
mixFile = open('tkweb/apps/drinks/drinkskort/mixing_drinks.pdf', "rb")