douping1993 2014-06-09 08:08
浏览 1929
已采纳

golang-如何从golang服务器在浏览器中下载文件?

My code get file from remote url and download file in browser:

func Index(w http.ResponseWriter, r *http.Request) {
    url := "http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png"

    ...

    resp, err := client.Get(url)
    if err != nil {
        fmt.Println(err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(len(body))
    //download the file in browser

}

func main() {
    http.HandleFunc("/", Index)
    err := http.ListenAndServe(":8000", nil)

    if err != nil {
        fmt.Println(err)
    }
}

code: http://play.golang.org/p/x-EyR2zFjv

Get file is ok, but how to downloaded it in browser?

Thanks.

  • 写回答

1条回答 默认 最新

  • duanqiao1961 2014-06-09 08:36
    关注

    To make the browser open the download dialog, add a Content-Disposition and Content-Type headers to the response:

    w.Header().Set("Content-Disposition", "attachment; filename=WHATEVER_YOU_WANT")
    w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
    

    Do this BEFORE sending the content to the client. You might also want to copy the Content-Length header of the response to the client, to show proper progress.

    To stream the response body to the client without fully loading it into memory (for big files this is important) - simply copy the body reader to the response writer:

    io.Copy(w, resp.Body)
    

    io.Copy is a nice little function that take a reader interface and writer interface, reads data from one and writes it to the other. Very useful for this kind of stuff!

    I've modified your code to do this: http://play.golang.org/p/v9IAu2Xu3_

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码