扣丁书屋

http.ServeFile强制浏览器下载文件并指定下载文件的文件名

通过在调用`http.ServerFile`以前,设置HTTP头,通知浏览器下载文件,并指定文件名
// Download forces response for download file.
// it prepares the download response header automatically.
func (output *BeegoOutput) Download(file string, filename ...string) {
    // check get file error, file not found or other error.
    if _, err := os.Stat(file); err != nil {
        http.ServeFile(output.Context.ResponseWriter, output.Context.Request, file)
        return
    }

    var fName string
    if len(filename) > 0 && filename[0] != "" {
        fName = filename[0]
    } else {
        fName = filepath.Base(file)
    }
    output.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(fName))
    output.Header("Content-Description", "File Transfer")
    output.Header("Content-Type", "application/octet-stream")
    output.Header("Content-Transfer-Encoding", "binary")
    output.Header("Expires", "0")
    output.Header("Cache-Control", "must-revalidate")
    output.Header("Pragma", "public")
    http.ServeFile(output.Context.ResponseWriter, output.Context.Request, file)
}

手机扫码阅读