Golang将文件的名称传递给浏览器/客户端。

huangapple go评论92阅读模式
英文:

Golang communicating the name of the file served to the browser/client

问题

我正在使用golang动态地提供一些文件,并且以下代码处理了文件的实际提供:

data, err := ioutil.ReadFile(file.Path)
logo.RuntimeError(err)
http.ServeContent(w, r, file.Name, time.Now(), bytes.NewReader(data))

在上述代码中,"file"只是一个自定义结构,保存了有关文件的各种信息。

这段代码的唯一问题是,每当我调用特定的处理程序时,它会导致我下载一个名为"download"的文件。我想给用户下载的文件一个自定义的名称,或者以一种尽可能与浏览器中立的方式表示我希望文件具有某个特定的名称。

我猜这可以通过使用w.WriteHeader来实现?但是我找不到任何示例或清晰的指南来说明如何做到这一点。

英文:

I'm serving some files dynamically using golang and the following code handles the actual serving of files:

		data, err := ioutil.ReadFile(file.Path)
		logo.RuntimeError(err)
		http.ServeContent(w, r, file.Name, time.Now(), bytes.NewReader(data))

Within the previous code "file" is simply a custom struct holding various information about the file.

The only problem with this code is that it results in me downloading a file called "download" whenever I call the specific handler. I'd like to give the file the user is downloading a custom name, or, rather, signify in a way that is as browser neutral as possible that I want the file to have a certain name.

I assume this might be doable using w.WriteHeader ? But I've been unable to find any examples or clear guidelines on how to do this.

答案1

得分: 12

在提供内容之前,设置内容描述头部:

f, err := os.Open(file.Path)
if err != nil {
    // 处理错误
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
     // 处理错误
}
w.Header().Set("Content-Disposition", "attachment; filename=YOURNAME")
http.ServeContent(w, r, file.Name, fi.ModTime(), f)

请注意,此代码直接将*os.File传递给ServeContent,而不是将整个文件读入内存。

通过调用ServeFile,可以进一步简化代码:

w.Header().Set("Content-Disposition", "attachment; filename=YOURNAME")
http.ServeFile(w, r, file.Name)
英文:

Set the content disposition header before serving the content:

f, err := os.Open(file.Path)
if err != nil {
    // handle error
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
     // handle error
}
w.Header().Set("Content-Disposition", "attachment; filename=YOURNAME")
http.ServeContent(w, r, file.Name, fi.ModTime(), f)

Note that this code passes an *os.File directly to ServeContent instead of reading the entire file to memory.

The code can be simplified further by calling ServeFile:

w.Header().Set("Content-Disposition", "attachment; filename=YOURNAME")
http.ServeFile(w, r, file.Name)

huangapple
  • 本文由 发表于 2017年6月13日 08:35:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/44510661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定