- 后端: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()
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);
})
}
function downloadFile() {
const anchor = document.createElement('a');
anchor.href = "/down";
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
}