Skip to content

Commit

Permalink
set utf-8 encoded filenames
Browse files Browse the repository at this point in the history
Characters in HTTP headers should be encoded with the ISO 8859-1
character set. So the previous implementation was wrong.
Browsers may have slightly different behaviours but this seems to work
in firefox.
  • Loading branch information
odrling committed Jul 15, 2024
1 parent 7f561a4 commit e767eaf
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
7 changes: 4 additions & 3 deletions server/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"mime/multipart"
"net/url"
"strconv"
"strings"

Expand Down Expand Up @@ -128,17 +129,17 @@ func Download(ctx context.Context, input *DownloadInput) (*huma.StreamResponse,
writer := ctx.BodyWriter()

stat, err := obj.Stat()
filename := stat.UserMetadata["Filename"]
filename := url.PathEscape(stat.UserMetadata["Filename"])
content_type := stat.UserMetadata["Type"]

main_type, _, _ := strings.Cut(content_type, "/")

ctx.SetHeader("Accept-Range", "bytes")
ctx.SetHeader("Content-Length", fmt.Sprintf("%d", stat.Size))
if main_type == "text" {
ctx.SetHeader("Content-Disposition", fmt.Sprintf("inline; filename=%s", filename))
ctx.SetHeader("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"; filename*=UTF-8''%s", filename, filename))
} else {
ctx.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
ctx.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"; filename*=UTF-8''%s", filename, filename))
}
ctx.SetHeader("Content-Type", content_type)

Expand Down
5 changes: 3 additions & 2 deletions server/producer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"mime/multipart"
"net/http/httptest"
"net/url"
"regexp"
"testing"

Expand Down Expand Up @@ -63,7 +64,7 @@ func TestUploadDownload(t *testing.T) {

test_data := []byte("hello world")
mime := mimetype.Detect(test_data)
filename := "test_file"
filename := "test file"
upload_data := uploadData(t, api, test_data, filename)

path := fmt.Sprintf("/%s", upload_data.Body.ID)
Expand Down Expand Up @@ -96,7 +97,7 @@ func TestUploadDownload(t *testing.T) {
}

matched, _ := regexp.MatchString(
fmt.Sprintf("filename=%s", regexp.QuoteMeta(filename)),
fmt.Sprintf("filename=\"%s\"", regexp.QuoteMeta(url.PathEscape(filename))),
content_disposition_header,
)

Expand Down

0 comments on commit e767eaf

Please sign in to comment.