diff --git a/context.go b/context.go index 582d00f2..ba5dc689 100644 --- a/context.go +++ b/context.go @@ -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) } diff --git a/context_test.go b/context_test.go index b82e04d5..925e628c 100644 --- a/context_test.go +++ b/context_test.go @@ -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) {