如何在 HTML 上上传 pdf 文件并在 FLASK 后端处理它?

我想知道将 PDF 文件作为 HTML 表单的输入并将其发送到我的 Flask 应用程序以处理该文件的最简单方法是什么。有什么方法可以避免将文件本地保存在我的系统上?


HTML:


<!doctype html>

    <title>Upload new File</title>

    <h1>Upload new File</h1>

    <form method=post enctype=multipart/form-data action = 'http://127.0.0.1:5000/uploadDoc'>

      <input type=file name=file>

      <input type=submit value=Upload>

    </form>

烧瓶:


app = Flask(__name__)


UPLOAD_FOLDER = 'C:\\Users\\Tanoy Majumdar\\Documents\\Chekk_OCR\\'



@app.route('/')

def hello_world():

    return 'Hello, World!'


@app.route('/uploadDoc', methods = ['POST', 'GET'])

def upload_file():

    print("Hello")

    if request.method == 'POST':

        # check if the post request has the file part

        if 'file' not in request.files:

            flash('No file part')

            return redirect(request.url)

        file = request.files['file']

        # if user does not select file, browser also

        # submit an empty part without filename

        if file.filename == '':

            flash('No selected file')

            return redirect(request.url)

        if file:

            filename = secure_filename(file.filename)

            #file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

    print(str(filename))  

    print (generate_kv(filename)) #generate_kv() converts pdf pages to images using pdf2image lib.

运行此应用程序时出现以下错误:


[2020-07-03 10:52:16,364] 应用程序错误:/uploadDoc [POST] 回溯异常(最近调用最后一次):文件“c:\users\tanoy majumdar\anaconda3\lib\site-packages\pdf2image \pdf2image.py”,第 436 行,在 pdfinfo_from_path 中引发 ValueError ValueError

慕田峪7331174
浏览 116回答 1
1回答

慕森卡

如果不知道论据需要什么,就不能 100% 回答这个问题generate_kv。文件名?一份文件?一条路径?字节流?所以我假设你必须传入file.stream,它是一个类似对象的文件,或者file.stream.read()是一个流。如果generate_kv需要路径,您可能必须file先将其保存到磁盘。顺便说一句,你file实际上是一种werkzeug.datastructure.filestorage类型——更多信息https://werkzeug.palletsprojects.com/en/1.0.x/datastructures/#werkzeug.datastructures.FileStorage更新我刚刚注意到,还有 whichfile._file实际上是一个真正的类文件对象,而file.streamis&nbsp;SpooledTemporaryFile。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python