使用JavaScript保存二进制数据时字节异常问题求助
问题分析与解决方案
问题根源
EF BF BD是UTF-8编码的替换字符(对应显示为�),说明axios默认将后端响应按UTF-8文本解析,遇到无法被UTF-8解码的字节时自动替换成该字符,导致二进制存档数据损坏。
解决方案
1. 前端axios请求添加二进制响应类型配置
修改axios请求,明确指定responseType为blob或arraybuffer,让axios直接保留原始二进制数据,不做文本解析:
方案一:使用blob类型
downloadSavefile(){ axios.get("http://127.0.0.1:5000/export/" + this.characterData.id, { responseType: 'blob' // 关键配置:指定响应为Blob类型 }) .then(response => { const a = document.createElement("a"); const blob = response.data; // 直接使用返回的Blob对象 const url = window.URL.createObjectURL(blob); a.href = url; a.download = this.characterData.name + ".bin"; a.click(); window.URL.revokeObjectURL(url); }) },
方案二:使用arraybuffer类型
downloadSavefile(){ axios.get("http://127.0.0.1:5000/export/" + this.characterData.id, { responseType: 'arraybuffer' // 关键配置:指定响应为ArrayBuffer类型 }) .then(response => { const a = document.createElement("a"); const blob = new Blob([response.data], { type: "application/octet-stream" }); const url = window.URL.createObjectURL(blob); a.href = url; a.download = this.characterData.name + ".bin"; a.click(); window.URL.revokeObjectURL(url); }) },
2. 后端Flask接口优化(可选但推荐)
在send_file中明确指定mimetype和as_attachment=True,确保响应头正确标识二进制文件,避免浏览器误解析:
return send_file(filepath, mimetype='application/octet-stream', as_attachment=True)
验证
修改后重新测试,对比前后端生成的文件字节码,EF BF BD替换字符将不再出现,二进制数据会完整保留。
内容的提问来源于stack exchange,提问作者Kevin Müller
相关产品推荐
相关产品推荐

