如何在Django

时间:2018-02-10 11:58:03

标签: python django python-3.x file-upload pypdf2

我正在尝试创建一个简单的django应用程序,它从用户那里获取一些PDF文件然后读取其内容。到目前为止,我已经编写了如下所述的代码,但它似乎没有用。它在此行PyPDF2.PdfFileReader(open(filename))

处产生错误
  

TypeError:预期的str,bytes或os.PathLike对象,而不是TemporaryUploadedFile

的index.html

<input type="file" name="fupload" multiple>

view.py

if request.method == 'POST':
        files = request.FILES.getlist('fupload')

        pdf_data = []
        for filename in files:
            read_pdf = PyPDF2.PdfFileReader(open(filename))
            page = read_pdf.getPage(0)
            page_content = page.extractText()
            pdf_data.append(page_content)

任何人都可以告诉我我做错了什么。提前致谢

1 个答案:

答案 0 :(得分:0)

您需要将views.py修改为此:

if request.method == 'POST' and request.FILES['myfile']:

        pdfFileObj = request.FILES['myfile'].read() 
        pdfReader = PyPDF2.PdfFileReader(io.BytesIO(pdfFileObj))
        NumPages = pdfReader.numPages
        i = 0
        content = []
        while (i<NumPages):
            text = pdfReader.getPage(i)
            content.append(text.extractText())
            i +=1