在搭建Flask服务器时,我们可以尝试接收用户上传的文件
imagefile = flask.request.files['imagefile']
filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
werkzeug.secure_filename(imagefile.filename)
filename = os.path.join(UPLOAD_FOLDER, filename_)
imagefile.save(filename)
logging.info('Saving to %s.', filename)
image = exifutil.open_oriented_im(filename)
当我看着Klein
文档,我见过http://klein.readthedocs.io/en/latest/examples/staticfiles.html
,但这似乎是从 Web 服务提供文件,而不是接收已上传到 Web 服务的文件。如果我想让我的Klein
服务器能够接收abc.jpg
并将其保存在文件系统中,是否有任何文档可以指导我实现该目标?
As Liam Kelly
评论,片段来自这个帖子 http://www.cristinagreen.com/uploading-files-using-twisted-web.html应该管用。使用cgi.FieldStorage
无需显式发送即可轻松发送文件元数据。 Klein/Twisted 方法看起来像这样:
from cgi import FieldStorage
from klein import Klein
from werkzeug import secure_filename
app = Klein()
@app.route('/')
def formpage(request):
return '''
<form action="/images" enctype="multipart/form-data" method="post">
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</form>
'''
@app.route('/images', methods=['POST'])
def processImages(request):
method = request.method.decode('utf-8').upper()
content_type = request.getHeader('content-type')
img = FieldStorage(
fp = request.content,
headers = request.getAllHeaders(),
environ = {'REQUEST_METHOD': method, 'CONTENT_TYPE': content_type})
name = secure_filename(img[b'datafile'].filename)
with open(name, 'wb') as fileOutput:
# fileOutput.write(img['datafile'].value)
fileOutput.write(request.args[b'datafile'][0])
app.run('localhost', 8000)
无论出于何种原因,我的 Python 3.4 (Ubuntu 14.04) 版本cgi.FieldStorage
不返回正确的结果。我在 Python 2.7.11 上测试了它,它工作得很好。话虽如此,您还可以在前端收集文件名和其他元数据,并将它们通过 ajax 调用发送给 klein。这样您就不必在后端进行太多处理(这通常是一件好事)。或者,您可以了解如何使用 werkzeug 提供的实用程序。功能werkzeug.secure_filename
and request.files
(ie. FileStorage
)实施或重新创建并不是特别困难。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)