我有一個二進制文件(pickle確切地說是python文件)。每當請求這樣的文件時,我都會在服務器端創建一個文件,然后通過 Flask 將其send_file作為 AJAX 請求發送到客戶端。接下來,我需要自動下載這個文件到客戶端,所以我使用了這個答案。問題在于,服務器上創建的文件大小通常為300 Bytes,而客戶端下載的文件大小>500 Bytes。另外,每當我嘗試重用 pickle 文件時,它都不會加載,并給出錯誤:_pickle.UnpicklingError: invalid load key, '\xef'.然而,服務器文件是無縫加載的。所以,問題是,客戶端文件在傳輸過程中被損壞。我認為jsblob可能是罪魁禍首。有人見過這樣的事情嗎?處理 AJAX 的服務器端代碼(flask)@app.route("/_exportTest",methods=['POST'])def exportTest(): index = int(request.form['index']) path = g.controller.exportTest(testID=index) logger.debug("Test file path :"+path) return send_file(path) #this is wrong somehow關于exportTest功能:def exportTest(self,testName): dic = dict() dic['screenShot'] = self.screenShot #string dic['original_activity'] = self.original_activity #string dic['steps'] = self.steps #list of tuples of strings if self.exportFilePath=='.': #this is the case which will be true filePath = os.path.join(os.getcwd(),testName) else: filePath = os.path.join(os.getcwd(),self.exportFilePath,testName) logger.debug("filePath :"+filePath) try: pickle.dump(dic,open(filePath,"wb"),protocol=pickle.HIGHEST_PROTOCOL) except Exception as e: logger.debug("Error while pickling Test.\n Error :"+str(e)) #No such error was printed return filePath
1 回答

FFIVE
TA貢獻1797條經驗 獲得超6個贊
補充道:
xhrFields: {
? ? responseType:'blob'
},
在 AJAX 請求中,這為我解決了問題。
我完全不知道為什么會這樣,所以有人可以給出比這更好的答案嗎?
在MDN 文檔中:
The values supported by responseType are the following:
An empty responseType string is treated the same as "text", the default type.
arraybuffer
The response is a JavaScript ArrayBuffer containing binary data.
blob
The response is a Blob object containing the binary data.
...
添加回答
舉報
0/150
提交
取消