我有一个二进制文件(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
提交
取消