golang http.ServeFile 如何修改下载的文件名?

我尝试请求动态资源,比如 下载 http://localhost/files/download?filename=a.txt 尝试下载a.txt但是下载下来默认的文件名都是download,在下载时已经做了: w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; \"filename=%s\"", "a.txt")) 但是仍然没有修改,想问下各位大侠这是为什么呢 ?

共 3 个回复


Maverick

w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", "a.txt"))
w.Header().Add("Content-Type", "application/octet-stream")
# 0

qingo

看beego的download

// 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)
}
# 1