如何解析Content-Disposition头以获取文件名属性?

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

How can I parse the Content-Disposition header to retrieve the filename property?

问题

使用Go语言,您可以如何解析从HTTP HEAD请求中获取的Content-Disposition头部,以获取文件的文件名?

此外,我如何从HTTP HEAD响应中检索头部本身?像这样的代码是否正确?

resp, err := http.Head("http://example.com/")
//处理错误
contentDisposition := resp.Header.Get("Content-Disposition")

mime/multipart包在Part类型上指定了一个返回文件名的方法(称为FileName),但我不清楚应该如何构造一个Part,或者从哪里获取。

英文:

Using go, how can I parse the Content-Disposition header retrieved from an http HEAD request to obtain the filename of the file?

Additionally, how do I retrieve the header itself from the http HEAD response? Is something like this correct?

resp, err := http.Head("http://example.com/")
//handle error
contentDisposition := resp.Header.Get("Content-Disposition")

The mime/multipart package specifies a method on the Part type that returns the filename (called FileName), but it's not clear to me how I should construct a Part, or from what.

答案1

得分: 35

你可以使用mime.ParseMediaType函数解析Content-Disposition头部。

disposition, params, err := mime.ParseMediaType(`attachment;filename="foo.png"`)
filename := params["filename"] // 设置为"foo.png"

这个方法也适用于头部中的Unicode文件名(例如Content-Disposition: attachment;filename*="UTF-8''fo%c3%b6.png")。

你可以在这里进行实验:http://play.golang.org/p/AjWbJB8vUk

英文:

You can parse the Content-Disposition header using the mime.ParseMediaType function.

disposition, params, err := mime.ParseMediaType(`attachment;filename="foo.png"`)
filename := params["filename"] // set to "foo.png"

This will also work for Unicode file names in the header (e.g. Content-Disposition: attachment;filename*="UTF-8''fo%c3%b6.png").

You can experiment with this here: http://play.golang.org/p/AjWbJB8vUk

huangapple
  • 本文由 发表于 2015年3月4日 06:17:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/28843047.html
匿名

发表评论

匿名网友

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

确定