From 599c542c5a8278c0ffe97e914f3f40d6a8c49fa0 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Mon, 5 Dec 2022 14:28:28 +0200 Subject: [PATCH] store the original uploaded file name as metadata --- tools/filesystem/filesystem.go | 9 +++++++++ tools/filesystem/filesystem_test.go | 14 ++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/tools/filesystem/filesystem.go b/tools/filesystem/filesystem.go index c4efd234..74a28e0a 100644 --- a/tools/filesystem/filesystem.go +++ b/tools/filesystem/filesystem.go @@ -133,8 +133,17 @@ func (s *System) UploadMultipart(fh *multipart.FileHeader, fileKey string) error // rewind f.Seek(0, io.SeekStart) + originalName := fh.Filename + if len(originalName) > 255 { + // keep only the first 255 chars as a very rudimentary measure + // to prevent the metadata to grow too big in size + originalName = originalName[:255] + } opts := &blob.WriterOptions{ ContentType: mt.String(), + Metadata: map[string]string{ + "original_filename": fh.Filename, + }, } w, err := s.bucket.NewWriter(s.ctx, fileKey, opts) diff --git a/tools/filesystem/filesystem_test.go b/tools/filesystem/filesystem_test.go index 906f18df..29c8e578 100644 --- a/tools/filesystem/filesystem_test.go +++ b/tools/filesystem/filesystem_test.go @@ -162,14 +162,24 @@ func TestFileSystemUploadMultipart(t *testing.T) { } defer fs.Close() - uploadErr := fs.UploadMultipart(fh, "newdir/newkey.txt") + fileKey := "newdir/newkey.txt" + + uploadErr := fs.UploadMultipart(fh, fileKey) if uploadErr != nil { t.Fatal(uploadErr) } - if exists, _ := fs.Exists("newdir/newkey.txt"); !exists { + if exists, _ := fs.Exists(fileKey); !exists { t.Fatalf("Expected newdir/newkey.txt to exist") } + + attrs, err := fs.Attributes(fileKey) + if err != nil { + t.Fatalf("Failed to fetch file attributes: %v", err) + } + if name, ok := attrs.Metadata["original_filename"]; !ok || name != "test" { + t.Fatalf("Expected original_filename to be %q, got %q", "test", name) + } } func TestFileSystemUpload(t *testing.T) {