简体   繁体   English

如何在 Django 中提供用户上传的 pdf 文件?

[英]How to Serve User-Uploaded pdf Files in Django?

I am attempting to display user uploaded PDF files in Django.我试图在 Django 中显示用户上传的 PDF 文件。 I am successfully able to display images, but not pdf files .我能够成功显示图像,但不能显示 pdf 文件

On the landing page, a user is being asked to fill out a Form:在登录页面上,要求用户填写表格:

class Profile_Form(forms.ModelForm):
    class Meta:
        model = User_Profile
        fields = [
        'fname',
        'lname',
        'technologies',
        'email',
        'display_picture'
        ]

I built a model that sets the display_picture to be a simple FileField.我构建了一个 model 将 display_picture 设置为一个简单的 FileField。

class User_Profile(models.Model):
    display_picture = models.FileField()

    def __str__(self):
        return self.fname

On the view (for both landing page and display of pdf/image, I am sending the user to the details.html after they submit their form在视图上(对于登陆页面和 pdf/图像的显示,我将用户发送到 details.html 在他们提交表单后

IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg', 'pdf']

def create_profile(request):

    # Create Form
    form = Profile_Form()

    # If Request is a POST, User needs to be Directed Somwehwere
    if request.method == 'POST':

        # Form Information is extracted from Forms.py
        form = Profile_Form(request.POST, request.FILES)
        if form.is_valid():
            user_pr = form.save(commit=False)
            user_pr.display_picture = request.FILES['display_picture']
            File_Upload_Name = str(request.FILES['display_picture'])
            print("File Name:", File_Upload_Name)

            BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            print("Base Dir: ", BASE_DIR)

            MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
            print("Media Root: ", MEDIA_ROOT)

            # Define Invoice Path
            invoice_path = File_Upload_Name
            user_pr.invoice_path = invoice_path

            # Copy File
            # copyfile("../media/" + user_pr.invoice_path, "../static/" + user_pr.invoice_path)


            print("Invoice Path: ", user_pr.invoice_path)

            # Grab the File Type (Should be ZIP)
            file_type = user_pr.display_picture.url.split('.')[-1]
            file_type = file_type.lower()

            # Confirm the File Type is Correcr
            if file_type not in IMAGE_FILE_TYPES:

                #If not, send user to the Error Page
                return render(request, 'profile_maker/error.html')

            #
            user_pr.save()

            # If file_type is correct and User Performs a POST, return request,
            # Details HTML, and User_PR Dictionary
            return render(request, 'profile_maker/details.html',
                          {'user_pr': user_pr})

    context = {"form": form, }
    return render(request, 'profile_maker/create.html', context)


Below is the HTML code for displaying the pdf.下面是用于显示 pdf 的 HTML 代码。 When user_pr.display_picture.url is media/filename.pdf, nothing is displayed, yet when user_pr.display_picture.url is media/imagename.jpg an image is displayed.当 user_pr.display_picture.url 是 media/filename.pdf 时,什么都没有显示,然而当 user_pr.display_picture.Z572D4E421E5E6B9BC11D815E8A02710EE004E1D937494D09Z 是 media/filename. Also worth nothing that the GET Request for media/filename.pdf (user_pr.display_picture.url) receives a 200 code.媒体/文件名的 GET 请求也毫无价值。pdf (user_pr.display_picture.url) 收到 200 代码。

  <p>Document being Analyzed: {{user_pr.invoice_path}}</p>
    <embed src="{{user_pr.display_picture.url}}" width="800px" height="2100px" />
    <img src="{{user_pr.display_picture.url}}" width="800px" height="2100px" />

    <embed src="{% static user_pr.invoice_path %}" width="800px" height="2100px" />
  <p>

May be you require to specify the content type.可能您需要指定内容类型。

For pdf content_type='application/pdf'对于 pdf content_type='application/pdf'

Try something like below (Not tested..)试试下面的东西(未测试..)

if file_type == 'pdf':
    return render(request, 'profile_maker/details.html',{'user_pr': user_pr},content_type='application/pdf')
else:
    return render(request, 'profile_maker/details.html',{'user_pr': user_pr})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Django中对用户上传的文件应用读/写权限 - How to apply read/write permissions to user-uploaded files in Django 使用 Dokku 制作 Django 用户上传的媒体文件 - Django user-uploaded media files in production with Dokku 如何链接到Django模板中的用户上传的个人资料图片(ImageField)? - How to link to user-uploaded profile pictures (ImageField) in Django templates? 如何将特定用户分配给用户上传的文件,以便他们可以对其进行修改/删除(Django + Apache) - How do I assign specific users to a user-uploaded file so they can modify it/delete it (Django + Apache) 如何在Django中提供以前上传的视频文件 - How to serve previously uploaded video files in Django Django-如何在生产中为用户上传的内容提供服务 - Django - How to serve user uploaded content in production 如何放置一种格式,在该格式中分析用户上传的文件,然后将其显示在新的url上? - How can I put in a form where user-uploaded files are parsed and then displayed on a new url? Flask - 将用户上传的图像提供给网页 - Flask - Serving user-uploaded images to the webpage 解除用户上传的 PDF 的最佳方法 - Best way to disarm user-uploaded PDFs 在 django 中打开一个用户上传的 PDF - Opening a user uploaded PDF in django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM