2014-06-09 08:08 阅读 648


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

func Index(w http.ResponseWriter, r *http.Request) {
    url := ""


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

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

    //download the file in browser


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

    if err != nil {


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


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanqiao1961 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:

    点赞 评论 复制链接分享