我想制作一个多文件上传表单.我使用jQuery File Uploader.我的服务器端代码:
@app.route("/new/photogallery",methods=["POST"])
def newPhotoGallery():
print request.files
Run Code Online (Sandbox Code Playgroud)
我尝试了两件事:
正常提交表格:
当我正常提交表格时,会打印:
ImmutableMultiDict([('post_photo_gallery', FileStorage: u'' ('application/octet-stream'))])
使用AJAX提交表单:
当我使用AJAX提交表单时,它会打印:
ImmutableMultiDict([])
我的第一个问题是:为什么AJAX请求和正常请求之间存在差异.
我的第二个问题是:我如何处理这个application/octet-stream请求Flask/Python
我的第三个问题是:这是一个好用的方法application/octet-stream吗?
顺便说一下,我不太了解application/octet-stream.非常感谢你.
小智 2
我无法使用application/octet-stream类型帖子来获取请求,但multipart/form-data过去曾使用类型表单来使用 Flask 上传图像。
我扩展了我过去所做的事情来支持多个上传文件,并且这已经利用了 werkzeug 的FileStorage对象。
这里的关键是设置一个基于帖子的路由,该路由从表单中查找请求元素。这应该允许您通过标准表单或 AJAX 调用 POST 到路由。
下面是一个使用表单的简化示例:
视图模板:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
{% if err %}
<h4>{{ err }}</h4>
{% endif %}
<form action="/" method=POST enctype=multipart/form-data id="fileupload">
<input type="file" name="files" data-url="/" multiple>
<input type=submit value=Post>
</form>
{% if files %}
{% for file in files %}
<p>Uploaded: <b>{{ file }}</b> </p>
{% endfor %}
{% endif %}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
烧瓶应用程序
from flask import Flask, request, render_template
from werkzeug import secure_filename, FileStorage
import os
# Flask functions
app = Flask(__name__)
app.config.from_object(__name__)
DEBUG = True
# add this so that flask doesn't swallow error messages
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route('/', methods=['GET', 'POST'])
def uploader():
if request.method =='POST' and request.files.getlist('files'):
up_file_list = []
# Iterate the through a list of files from the form input field
for a_file in request.files.getlist('files'):
if a_file.filename:
# Validate that what we have been supplied with is infact a file
if not isinstance(a_file, FileStorage):
raise TypeError("storage must be a werkzeug.FileStorage")
# Sanitise the filename
a_file_name = secure_filename(a_file.filename)
# Build target
a_file_target = os.path.join('/tmp/', a_file_name)
# Save file
a_file.save(a_file_target)
up_file_list.append(a_file_name)
# Return template
if up_file_list:
return render_template('uploader.html', err=None, files=up_file_list)
else:
return render_template('uploader.html', err='No Files Uploaded', files=None)
else:
return render_template('uploader.html', err=None, files=None)
# application execution
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7421 次 |
| 最近记录: |