【错误记录/js】保存octet-stream为文件后数据错乱

说在前面

  • 后端: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:"B"`
    		C string `json:"C"`
    	}
    
    	a := &A{
    		B: 746,
    		C: "sjdfksdjlvsj",
    	}
    
    	fileName := "aaa"
    	c.Header("Content-Type", "application/octet-stream")
    	c.Header("Content-Disposition", "attachment; filename="+fileName)
    	// 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.txt"
        anchor.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);
        }
    
  • 结果一致了
    在这里插入图片描述

其他

  • 具体为什么会导致这种差异,查了一些资料,大概率是编码上的问题,后面有时间再详细查。
  • 17
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值