fix: change multipart.File -> io.ReadSeeker

This commit is contained in:
Rohan Verma
2019-10-18 13:15:03 +05:30
parent 4f0bc0042e
commit 3d5b071ef7
+17 -14
View File
@@ -38,7 +38,7 @@ type UploadInput struct {
ObjectKey string ObjectKey string
FileName string FileName string
ContentType string ContentType string
Body multipart.File Body io.ReadSeeker
} }
// UploadResponse receives the following XML // UploadResponse receives the following XML
@@ -143,19 +143,18 @@ func (s3 *S3) getClient() *http.Client {
return s3.Client return s3.Client
} }
func detectFileSize(body multipart.File) int64 { func detectFileSize(body io.Seeker) (int64, error) {
switch r := body.(type) { pos, err := body.Seek(0, 1)
case io.Seeker: if err != nil {
pos, _ := r.Seek(0, 1) return -1, err
defer r.Seek(pos, 0)
n, err := r.Seek(0, 2)
if err != nil {
return -1
}
return n
} }
return -1 defer body.Seek(pos, 0)
n, err := body.Seek(0, 2)
if err != nil {
return -1, err
}
return n, nil
} }
// SetClient can be used to set the http client to be // SetClient can be used to set the http client to be
@@ -173,12 +172,16 @@ func (s3 *S3) SetClient(client *http.Client) *S3 {
// FileUpload makes a POST call with the file written as multipart // FileUpload makes a POST call with the file written as multipart
// and on successful upload, checks for 200 OK. // and on successful upload, checks for 200 OK.
func (s3 *S3) FileUpload(u UploadInput) (UploadResponse, error) { func (s3 *S3) FileUpload(u UploadInput) (UploadResponse, error) {
fSize, err := detectFileSize(u.Body)
if err != nil {
return UploadResponse{}, err
}
policies, err := s3.CreateUploadPolicies(UploadConfig{ policies, err := s3.CreateUploadPolicies(UploadConfig{
UploadURL: fmt.Sprintf(s3.URIFormat, s3.Region, u.Bucket), UploadURL: fmt.Sprintf(s3.URIFormat, s3.Region, u.Bucket),
BucketName: u.Bucket, BucketName: u.Bucket,
ObjectKey: u.ObjectKey, ObjectKey: u.ObjectKey,
ContentType: u.ContentType, ContentType: u.ContentType,
FileSize: detectFileSize(u.Body), FileSize: fSize,
MetaData: map[string]string{ MetaData: map[string]string{
"success_action_status": "201", // returns XML doc on success "success_action_status": "201", // returns XML doc on success
}, },