Skip to content

Commit

Permalink
Attach file size to each multipart file converted to http request.
Browse files Browse the repository at this point in the history
Read/set size for each Readerfile on parsing file.
  • Loading branch information
Eric Chen committed Oct 9, 2019
1 parent 0d386ae commit 3b02491
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
9 changes: 7 additions & 2 deletions multifilereader.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,6 @@ func (mfr *MultiFileReader) Read(buf []byte) (written int, err error) {
dispositionPrefix = "form-data; name=\"file\""
}

header.Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", dispositionPrefix, filename))

var contentType string

switch f := entry.Node().(type) {
Expand All @@ -115,8 +113,15 @@ func (mfr *MultiFileReader) Read(buf []byte) (written int, err error) {
header.Set("Content-Type", contentType)
if rf, ok := entry.Node().(FileInfo); ok {
header.Set("abspath", rf.AbsPath())
// attach file size to content-disposition when available
// according to https://tools.ietf.org/html/rfc2183
if stat := rf.Stat(); stat != nil {
dispositionPrefix += fmt.Sprintf("; size=%d", stat.Size())
}
}

header.Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", dispositionPrefix, filename))

_, err := mfr.mpWriter.CreatePart(header)
if err != nil {
return 0, err
Expand Down
22 changes: 19 additions & 3 deletions multipartfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"mime/multipart"
"net/url"
"path"
"strconv"
"strings"
)

Expand All @@ -18,7 +19,8 @@ const (
applicationSymlink = "application/symlink"
applicationFile = "application/octet-stream"

contentTypeHeader = "Content-Type"
contentTypeHeader = "Content-Type"
contentDispositionHeader = "Content-Disposition"
)

type multipartDirectory struct {
Expand Down Expand Up @@ -101,10 +103,24 @@ func (w *multipartWalker) nextFile() (Node, error) {

return NewLinkFile(string(out), nil), nil
default:
return &ReaderFile{
rf := &ReaderFile{
reader: part,
abspath: part.Header.Get("abspath"),
}, nil
}
cdh := part.Header.Get(contentDispositionHeader)
_, params, err := mime.ParseMediaType(cdh)
if err != nil {
return nil, err
}
// ignore if size is not available
if size, ok := params["size"]; ok {
fsize, err := strconv.ParseInt(size, 10, 64)
if err != nil {
return nil, err
}
rf.fsize = fsize
}
return rf, nil
}
}

Expand Down

0 comments on commit 3b02491

Please sign in to comment.