以下代码使用Bottle框架成功上传图像文件。
upload = bottle.request.files.get("filPhoto01")
if upload is not None:
name, ext = os.path.splitext(upload.filename)
if ext not in ('.png','.jpg','.jpeg'):
return "File extension not allowed."
save_path = "/tmp/abc".format(category=category)
if not os.path.exists(save_path):
os.makedirs(save_path)
file_path = "{path}/{file}".format(path=save_path, file=upload.filename)
with open(file_path, 'w') as open_file:
open_file.write(upload.file.read())
但是,当我尝试在上传后手动打开此文件时,我无法打开该文件。我可以看到上传文件的图标大小正确(暗示整个图像已上传),但我无法在MS绘画等任何应用程序中查看它。
我也尝试在我的Web应用程序中引用该文件,但它也没有呈现在那里。什么可能是错的?
答案 0 :(得分:1)
只是一个猜测,但因为它听起来像你在Windows上,你会想要以二进制模式编写文件:
with open(file_path, 'wb') as open_file:
(另外,你没有提到你的Python版本,但是在Python 3中的FYI你甚至需要在Linux上使用二进制模式。)