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

2337次阅读  |  发布于4年以前
// 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)
}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8