有没有一种简单的方法来处理使用python的html表单上传?

时间:2014-11-25 21:14:14

标签: python

众所周知,在php中上传文件的最简单方法是使用以下代码:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

我想要一个方法来上传尽可能最简单的python文件,当前目录中的文件如下:

import anyuploadmodule
upload(file)

是否有这样的模块可以做到这一点?

1 个答案:

答案 0 :(得分:3)

没有任何 简单的东西,但像Flask这样的微框架可以是轻量级和简单的起点。您需要查看documentation。这是一个让你入门的片段:

# -*- coding: utf-8 -*-

import os

from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/some/path/'

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(url_for('uploaded_file', filename=filename))
    return '''<!doctype html>
              <title>Upload new File</title>
              <h1>Upload new File</h1>
              <form action="" method=post enctype=multipart/form-data>
                <p><input type=file name=file>
                <input type=submit value=Upload>
              </form>'''

if __name__ == '__main__':
    app.run()