【发布时间】:2015-06-01 13:14:17
【问题描述】:
我运行 Python Flask 应用程序并希望实现将文件上传到服务器的可能性。 FileDrop.js 看起来很有希望完成这项任务,但是,我不能让它与 Flask 一起工作。
原因似乎是 Flask 期望文件通过 POST 以及用于从应用程序中识别文件的附加参数发送到服务器。我使用另一个文件上传框架jQuery filedrop:
<html>
<head>
<script type="text/javascript" src="https://github.com/weixiyen/jquery-filedrop/blob/master/jquery.filedrop.js"></script>
</head>
<body>
<fieldset id="zone">
<br><br>
<legend><strong>Drop one or more files inside...</strong></legend>
<br><br>
</fieldset>
<script type="text/JavaScript">
// when the whole document has loaded, call the init function
$(document).ready(init);
function init() {
var zone = $('#zone'),
message = $('.message', zone);
// send all dropped files to /upload on the server via POST
zone.filedrop({
paramname: 'file',
maxfiles: 200,
maxfilesize: 20,
url: '/upload',
}
}
</script>
</body>
</html>
paramname: 'file' 以某种方式随请求一起发送,以便在我的 Flask 应用程序中,我可以通过以下方式获取上传的文件:
@app.route('/upload', methods=['POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
file.save('myfile.ext')
return 'Done'
但是,如何使用FileDrop.js 获取我上传的文件?我在文档中看不到如何通过 POST 传递附加参数的可能性。当我按照文档中的最小示例进行操作时,例如
<html>
<head>
<script type="text/javascript" src="https://github.com/ProgerXP/FileDrop/blob/master/filedrop.js"></script>
</head>
<body>
<fieldset id="zone">
<legend>Drop a file inside...</legend>
<p>Or click here to <em>Browse</em>...</p>
</fieldset>
<script type="text/JavaScript">
// when the whole document has loaded, call the init function
$(document).ready(init);
function init() {
var options = {iframe: {url: '/upload'}}
var zone = new FileDrop('zone')
// Do something when a user chooses or drops a file:
zone.event('send', function (files) {
// FileList might contain multiple items.
files.each(function (file) {
// Send the file:
file.sendTo('/upload')
})
})
}
</script>
</body>
</html>
然后尝试在 Flask 中检查上传的文件:
@app.route('/uploadtest', methods=['POST'])
def uploadtest():
print(request.files)
return 'end'
request.files 现在是ImmutableMultiDict([]),我不知道如何从 Flask 访问它。有什么建议吗?
【问题讨论】:
标签: javascript python flask filedrop.js