Python Flask上传文件测试
常伟佳 人气:0Flask file upload代码
import os from flask import Flask, request, redirect, url_for, send_from_directory from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/tmp/flask-upload-test/' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: print 'no file' return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': print 'no filename' return redirect(request.url) if file and allowed_file(file.filename): 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> ''' @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) if __name__ == "__main__": app.run(debug=True)
上传测试
$ curl -F 'file=@"foo.png";filename="bar.png"' 127.0.0.1:5000
注意:使用上传文件功能的时候使用 POST form-data,参数名就是参数名(一般会提前约定好,而不是变化的文件名),参数的值是一个文件(这个文件正常是有文件名的)。
上传临时文件
有时候脚本生成了要上传的文件,但并没有留在本地的需求,所以使用临时文件的方式,生成成功了就直接上传。
使用 tempfile
tempfile 会在系统的临时目录中创建文件,使用完了之后会自动删除。
import requests import tempfile url = 'http://127.0.0.1:5000' temp = tempfile.NamedTemporaryFile(mode='w+', suffix='.txt') try: temp.write('Hello Temp!') temp.seek(0) files = {'file': temp} r = requests.post(url, files=files, proxies=proxies) finally: # Automatically cleans up the file temp.close()
使用 StringIO
或者直接使用 StringIO,可以直接在内存中完成整个过程。
import requests from StringIO import StringIO url = 'http://127.0.0.1:5000' temp = StringIO() temp.write('Hello Temp!') temp.seek(0) temp.name = 'hello-temp.txt' # StringIO 的实例没有文件名,需要自己手动设置,不设置 POST 过去那边的文件名会是 'file' files = {'file': temp} r = requests.post(url, files=files)
其他
补上发现的一段可以上传多个同名附件的代码:
files = [ ("attachments", (display_filename_1, open(filename1, 'rb'),'application/octet-stream')), ("attachments", (display_filename_2, open(filename2, 'rb'),'application/octet-stream')) ] r = requests.post(url, files=files, data=params)
参考
10.6. tempfile — Generate temporary files and directories — Python 2.7.12 documentation
加载全部内容