标签:hex index __name__ 文件上传 list ase quic 导致 ==
Cherrypy 版本: 18.0.1
由于某些特殊原因(可能是与标准兼容的问题),Cherrypy对上传文件的原文件名使用 ISO-8859-1 编码方式解码,导致非 ASCII 的文件名显示为乱码。
解决的方式也很简单,只需要对文件名使用 ISO-8859-1 编码然后在使用 UTF-8 重新解码即可。
以下是一个完整的例子:
1 from os import makedirs 2 from os.path import dirname, join as pathjoin, exists as pathexists 3 from cherrypy import expose, quickstart, request, config 4 5 HERE = dirname(__file__) 6 UPLOAD_FOLDER = pathjoin(HERE, ‘uploads‘) 7 8 9 def repaire_filename(filename): 10 return filename.encode(‘ISO-8859-1‘).decode(‘utf-8‘, ‘replace‘) 11 12 13 def save_uploadfiles(files, folder=UPLOAD_FOLDER): 14 if not pathexists(folder): 15 makedirs(folder) 16 if not isinstance(files, list): 17 files = [files] 18 for upload in files: 19 if not upload.filename: 20 continue 21 basename = repaire_filename(upload.filename) 22 filename = pathjoin(folder, basename) 23 with upload.file as upload_file, open(filename, ‘wb‘) as to_save: 24 while True: 25 buf = upload_file.read(8192) 26 if not buf: 27 break 28 to_save.write(buf) 29 30 31 @expose 32 def index(upload_files=None): 33 if request.method == ‘POST‘: 34 save_uploadfiles(upload_files) 35 return ‘‘‘ 36 <form method="POST" enctype="multipart/form-data"> 37 <div><input name="upload_files" type="file" /></div> 38 <div><input name="upload_files" type="file" /></div> 39 <div><input name="upload_files" type="file" /></div> 40 <input type="submit" /> 41 </form> 42 ‘‘‘ 43 44 45 if __name__ == ‘__main__‘: 46 quickstart(index)
标签:hex index __name__ 文件上传 list ase quic 导致 ==
原文地址:https://www.cnblogs.com/inpool/p/cherrypy_upload_files.html