英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论