Golang获取网络图片并返回给前端二进制流

获取网络图片并返回给前端二进制流,前端通过axios下载该图片二进制流,实现下载图片功能

后端:

func Download(c *gin.Context) {
    picName := c.DefaultQuery("copyright", "")
    picUrlBase := c.DefaultQuery("urlBase", "")
    h := c.DefaultQuery("h", "1080")
    w := c.DefaultQuery("w", "1920")
    fmt.Println(picName, picUrlBase)
    if picUrlBase == "" {
        c.JSON(http.StatusNotFound, nil)
        return
    }
    url := config.AppConfig.API.Baseurl + picUrlBase + "_" + w + "x" + h + ".jpg"
    imgData := utils.ReadImgData(url) //注意
    c.Header("Content-Type", "application/octet-stream")
    c.Header("Content-Disposition", "attachment; filename="+picName+".jpg")
    c.Header("Content-Transfer-Encoding", "binary")
    _, err := c.Writer.Write(imgData)
    if err != nil {
        return
    }
    return
}
func ReadImgData(url string) []byte {
    resp, err := http.Get(url)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    pix, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    return pix
}

前端:

download(item) {
      this.$axios.get('/download',{
        params:{
          "copyright": item.copyright,
          "urlBase": item.urlbase
        },
        responseType: 'blob'}
      ).then((data)=>{
        let blob = data.data
        let reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = item.copyright + ".jpg"
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      })
    }
标题:Golang获取网络图片并返回给前端二进制流
作者:Ne-21
文章地址:https://blog.gocos.cn/archives/204.html
转载请注明出处,谢谢!
THE END
分享
二维码
打赏
< <上一篇
下一篇>>