python後端寫下載文件, 這個時候出現了這個錯誤python
latin-1 codec cant encode characters in position 42-48: ordinal not in range256json
怎麼辦:後端
查原由: 發現文件名有中文名字, 因此致使錯誤, 編碼是latin-1編碼, 因此咱們須要解碼成unicode在編碼成latin-1app
先看代碼:tornado
這段代碼涉及python轉碼問題, 必定要注意編碼
FilePathName = self.get_argument("FilePathName", None) #獲取文件名 FileName = str(FilePathName.split("/")[-1]).strip() # 獲得文件名 latinFileName = FileName.encode("utf-8").decode("latin1") # 這句很關鍵, 要解析成latin-1才OK,這樣就不會報錯
class DownFileHandler(downBaseRequestHandler): @tornado.gen.coroutine def get(self, *args, **kwargs): if self.verifyFlag == 1 and self.status == 0: status = 2000 try: FilePathName = self.get_argument("FilePathName", None) FilePathName = MyBase64.decryption(unquote(FilePathName)) # 這句是解密 FileName = str(FilePathName.split("/")[-1]).strip() latinFileName = FileName.encode("utf-8").decode("latin1") # 這句很關鍵, 要解析成latin-1才OK,這樣就不會報錯 newFileName = str(int(time.time())) + "." + FileName.split(".")[1] # 第二種方式就是換一個文件名 self.set_header("Content-Type", "application/x-zip-compressed") # -----<或者這麼寫> ----- # # self.set_header("Content-Type", "application/octet-stream") self.set_header("Content-Disposition", "attachment; filename=%s" % latinFileName) f = open(FilePathName, 'rb') while True: b = f.read(8096) if not b: break else: self.write(b) self.flush() f.close() except Exception as e: e = FormatErrorCode(e) my_log.error(e) status = int(e[0]) self.write(json.dumps(result(status=status))) self.finish() else: self.write(json.dumps(result(status=4005))) self.finish()