我运行Python应用程序,并希望实现将文件上传到服务器的可能性。对于这个任务,FileDrop.js看起来很有希望,但是,我没有让它与烧瓶一起工作。
这样做的原因似乎是,Flask期望通过POST将文件发送到服务器,以及用于从应用程序中识别文件的附加参数。我使用了另一个文件上传框架jQuery文件来完成这个任务
<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'以某种方式与请求一起发送,以便在我的烧瓶应用程序中,我可以通过以下方式获得上传的文件:
@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>然后试着检查烧瓶中上传的文件:
@app.route('/uploadtest', methods=['POST'])
def uploadtest():
print(request.files)
return 'end'request.files现在是一个ImmutableMultiDict([]),我不知道如何从瓶中访问它。有什么建议吗?
发布于 2015-08-22 19:50:06
实际上,我正在处理同样的问题,也许可以帮助你完成我的决定。
首先,只有在使用特定编码和类型从表单发送数据时,烧瓶请求上的files属性才会出现。FileDrop不使用它,因此请求中的files属性应该是空的。
标签被标记为enctype=multipart/ form -data,并以该形式放置一个标记。http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
FileDrop似乎没有像dropzone.js使用这个表单那样发送它。我所做的就是查看FileDrop提出的网络请求。这是个帖子。我可以看出它是作为一个职位处理的。数据在哪里?在浏览器中的网络请求中,我可以看到一个名为X-File-Name的标题,它是上传的文件的url引号。我可以在请求对象中访问它。
fileName = urlparse.unquote(request.headers['X-File-Name'])实际数据在哪里?在邮件请求的正文里。这是在request.data中--以任何编码格式上传的整个文件。
foo = open('/tmp/%s' % fileName, 'w')
foo.write(request.data)
foo.close()这只是一个例子,但有效。显然,您仍然应该遵循我为保护该文件名而链接的烧瓶“文件上传”页面上的安全提示,但否则就只有这些了。
使用post主体的直接缺点是每个请求只有一个文件,但这对我的特定应用程序来说并不是什么大问题。希望这能有所帮助。
https://stackoverflow.com/questions/30574525
复制相似问题