I run a Python Flask application and want to implement the possibility to upload files to the server. FileDrop.js looks promising for this task, however, I do not get it to work together with Flask.
The reason for this seems to be that Flask expects that the file is send to the server via POST along with an additional parameter that is used to identify the file from the application. I got this working using another file uploading framework, 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>
The paramname: 'file'
is sent somehow with the request so that in my Flask application, I can get the uploaded file via:
@app.route('/upload', methods=['POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
file.save('myfile.ext')
return 'Done'
However, how can I get my uploaded file using FileDrop.js? I don't see a possibility in the documentation how to pass an additional parameter via POST. When I follow the minimal examples from the documentation, for example
<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>
then trying to inspect the uploaded file in Flask:
@app.route('/uploadtest', methods=['POST'])
def uploadtest():
print(request.files)
return 'end'
request.files
is now a ImmutableMultiDict([])
and I don't know how to access it from Flask. Any suggestions?