Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download file in browser from Go server

Tags:

go

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?

like image 788
leiyonglin Avatar asked Jun 09 '14 08:06

leiyonglin


People also ask

How do I download from Golang server?

From the main menu, choose Tools | Deployment | Download from <default server>. GoLand will prompt you to overwrite local files, if any.

Where is Go downloaded?

You can find downloads on Android in My Files or File Manager. You can find these apps in the app drawer of your Android device. Within My Files or File Manager, navigate to the Downloads folder to find everything you downloaded.


1 Answers

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_

like image 111
Not_a_Golfer Avatar answered Sep 17 '22 17:09

Not_a_Golfer