网站建设html5模板,北京上海网站建设,提高网站建设管理水平,北辰做网站的公司目录 说在前面场景解决方式其他 说在前面 后端#xff1a;go、gin浏览器#xff1a;Microsoft Edge 120.0.2210.77 (正式版本) (64 位) 场景
前端通过点击按钮来下载一些文件#xff0c;但是文件内容是一些非文件形式存储的二进制数据。 后端代码 r : gin.Default()r.Stat… 目录 说在前面场景解决方式其他 说在前面 后端go、gin浏览器Microsoft Edge 120.0.2210.77 (正式版本) (64 位) 场景
前端通过点击按钮来下载一些文件但是文件内容是一些非文件形式存储的二进制数据。 后端代码 r : gin.Default()r.Static(/home, ./public)r.GET(/down, func(c *gin.Context) {type A struct {B uint json:BC string json:C}a : A{B: 746,C: sjdfksdjlvsj,}fileName : aaac.Header(Content-Type, application/octet-stream)c.Header(Content-Disposition, attachment; filenamefileName)// c.Header(Content-Transfer-Encoding, binary)c.Header(Cache-Control, no-cache)var save bytes.Buffer// 使用gob的序列化进行测试enc : gob.NewEncoder(save)enc.Encode(a)// 保存到本地用于对比file, err : os.OpenFile(test.txt, os.O_CREATE, 0)if err ! nil {fmt.Println(err)return}defer file.Close()file.Write(save.Bytes())// 返回到前端c.Data(http.StatusOK, application/octet-stream, save.Bytes())
})
r.Run() js代码
function downloadBlob(data) {console.log([data])const anchor document.createElement(a);document.body.appendChild(anchor);var url window.URL.createObjectURL(new Blob([data]));anchor.href url;anchor.download file.txtanchor.click();document.body.removeChild(anchor);
}
function downloadFileBlob() {// 使用axios请求数据axios.get(/down).then((response) {downloadBlob(response.data);})
}对比发现数据对不上(左js保存 右本地文件保存)
解决方式
尝试发现不需要使用axios直接使用链接就行 function downloadFile() {const anchor document.createElement(a);anchor.href /down;document.body.appendChild(anchor);anchor.click();document.body.removeChild(anchor);}结果一致了
其他
具体为什么会导致这种差异查了一些资料大概率是编码上的问题后面有时间再详细查。