Golang : Force download file example
For this tutorial, we will learn how to create a page that will force download a file to the client. Instead of waiting for the user to click the download link to a file, the server will force download the file with the help of meta refresh
.
In case the force download doesn't work... you still can offer a link for the visitor to click on to initiate the download process.
Here you go!
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
// change to your target filename
// that you want to force download to your visitor browser
var file = "img.pdf"
func Home(w http.ResponseWriter, r *http.Request) {
// We will force download after 2 seconds. If you want to increase the delay
// simply change 2 to whatever number you wanted.
html := "<html><meta http-equiv='refresh' content='2; url=http://localhost:8080/download' />"
html = html + "Downloading file now. If the download does not happen automagically. Please "
html = html + "<a href=" + file + ">click here</a></html>"
w.Write([]byte(html))
}
func ForceDownload(w http.ResponseWriter, r *http.Request) {
downloadBytes, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
}
// set the default MIME type to send
mime := http.DetectContentType(downloadBytes)
fileSize := len(string(downloadBytes))
// Generate the server headers
w.Header().Set("Content-Type", mime)
w.Header().Set("Content-Disposition", "attachment; filename="+file+"")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Transfer-Encoding", "binary")
w.Header().Set("Content-Length", strconv.Itoa(fileSize))
w.Header().Set("Content-Control", "private, no-transform, no-store, must-revalidate")
//b := bytes.NewBuffer(downloadBytes)
//if _, err := b.WriteTo(w); err != nil {
// fmt.Fprintf(w, "%s", err)
// }
// force it down the client's.....
http.ServeContent(w, r, file, time.Now(), bytes.NewReader(downloadBytes))
}
func main() {
http.HandleFunc("/", Home)
http.HandleFunc("/download", ForceDownload)
// SECURITY : Only expose the file permitted for download.
http.Handle("/"+file, http.FileServer(http.Dir("./")))
http.ListenAndServe(":8080", nil)
}
In the code above, change the file img.pdf
to whatever filename that you have on the same directory as the program.
Point your browser to localhost:8080
and if everything goes smoothly, you should see the message and the download action is initiated automagically after 2 seconds.
Happy coding!
References:
https://www.codeigniter.com/userguide/helpers/downloadhelper.html#force_download
See also : Golang : How to stream file to client(browser) or write to http.ResponseWriter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+22k Find and replace a character in a string in Go
+23.9k Golang : Convert uint value to string type
+7.8k Golang : Heap sort example
+18.9k Nginx + FastCGI + Go Setup.
+25.1k Golang : Encrypt and decrypt data with AES crypto
+13.8k Golang : How to check for empty array string or string?
+8.9k Golang : Convert octal value to string to deal with leading zero problem
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?
+4.5k Golang : Intercept, inject and replay HTTP traffics from web server
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+6.9k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+7.4k PHP : How to parse ElasticSearch JSON ?