mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
fix(context): encode spaces as %20 in FileAttachment filename*
This commit is contained in:
parent
43fe48e8a0
commit
cdfc5c62d5
@ -1364,7 +1364,10 @@ func (c *Context) FileAttachment(filepath, filename string) {
|
||||
if isASCII(filename) {
|
||||
c.Writer.Header().Set("Content-Disposition", `attachment; filename="`+escapeQuotes(filename)+`"`)
|
||||
} else {
|
||||
c.Writer.Header().Set("Content-Disposition", `attachment; filename*=UTF-8''`+url.QueryEscape(filename))
|
||||
// RFC 5987 ext-value: percent-encode everything outside attr-char.
|
||||
// url.QueryEscape writes a space as "+", which RFC 5987 decoders keep
|
||||
// as a literal "+", so encode spaces as "%20" instead.
|
||||
c.Writer.Header().Set("Content-Disposition", `attachment; filename*=UTF-8''`+strings.ReplaceAll(url.QueryEscape(filename), "+", "%20"))
|
||||
}
|
||||
http.ServeFile(c.Writer, c.Request, filepath)
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ import (
|
||||
"html/template"
|
||||
"io"
|
||||
"io/fs"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/http"
|
||||
@ -1698,6 +1699,23 @@ func TestContextRenderUTF8Attachment(t *testing.T) {
|
||||
assert.Equal(t, `attachment; filename*=UTF-8''`+url.QueryEscape(newFilename), w.Header().Get("Content-Disposition"))
|
||||
}
|
||||
|
||||
func TestContextRenderUTF8AttachmentWithSpaces(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
newFilename := "résumé final+v2.pdf"
|
||||
|
||||
c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)
|
||||
c.FileAttachment("./gin.go", newFilename)
|
||||
|
||||
contentDisposition := w.Header().Get("Content-Disposition")
|
||||
assert.Equal(t, `attachment; filename*=UTF-8''r%C3%A9sum%C3%A9%20final%2Bv2.pdf`, contentDisposition)
|
||||
|
||||
// RFC 5987 percent-decoding must give back the original name.
|
||||
_, params, err := mime.ParseMediaType(contentDisposition)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, newFilename, params["filename"])
|
||||
}
|
||||
|
||||
// TestContextRenderYAML tests that the response is serialized as YAML
|
||||
// and Content-Type is set to application/yaml
|
||||
func TestContextRenderYAML(t *testing.T) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user