Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add function support download file #53

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions render.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
// m.Get("/xml", func(r render.Render) {
// r.XML(200, Greeting{One: "hello", Two: "world"})
// })
//
// m.Get("/file/:filename", func(r render.Render, params martini.Params) {
// r.Download(params[filename])
// })
//
// m.Run()
// }
Expand Down Expand Up @@ -101,6 +105,8 @@ type Render interface {
Template() *template.Template
// Header exposes the header struct from http.ResponseWriter.
Header() http.Header
// Download forces response for download file, it prepares the download response header automatically.
Download(file string, filename ...string)
}

// Delims represents a set of Left and Right delimiters for HTML template rendering
Expand Down Expand Up @@ -326,6 +332,21 @@ func (r *renderer) Data(status int, v []byte) {
r.Write(v)
}

func (r *renderer) Download(file string,filename ...string ) {
r.Header().Set("Content-Description","File Transfer")
r.Header().Set("Content-Type","application/octet-stream")
if len(filename) > 0 && filename[0] != "" {
r.Header().Set("Content-Disposition", "attachment; filename="+filename[0])
} else {
r.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(file))
}
r.Header().Set("Content-Transfer-Encoding", "binary")
r.Header().Set("Expires", "0")
r.Header().Set("Cache-Control", "must-revalidate")
r.Header().Set("Pragma", "public")
http.ServeFile(r.ResponseWriter,r.req,file)
}

func (r *renderer) Text(status int, v string) {
if r.Header().Get(ContentType) == "" {
r.Header().Set(ContentType, ContentText+r.compiledCharset)
Expand Down