Skip to content

Commit

Permalink
feat: support parsing content type when uploading files
Browse files Browse the repository at this point in the history
  • Loading branch information
flywukong committed Nov 20, 2023
1 parent bcbc5c9 commit ac28a2e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
6 changes: 6 additions & 0 deletions cmd/cmd_object.go
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,12 @@ func uploadFile(bucketName, objectName, filePath, urlInfo string, ctx *cli.Conte
opts := sdktypes.CreateObjectOptions{}
if contentType != "" {
opts.ContentType = contentType
} else {
// parse the mimeType as content type
mimeType, err := getContentTypeOfFile(filePath)
if err == nil {
opts.ContentType = mimeType
}
}

visibity := ctx.Generic(visibilityFlag)
Expand Down
22 changes: 21 additions & 1 deletion cmd/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
Expand Down Expand Up @@ -111,7 +112,8 @@ const (
progressDelayPrintSize = 10 * 1024 * 1024
timeFormat = "2006-01-02T15-04-05.000000000Z"

printRateInterval = time.Second / 2
printRateInterval = time.Second / 2
bytesToReadForMIME = 512
)

var (
Expand Down Expand Up @@ -706,3 +708,21 @@ func convertAddressToLower(str string) string {
}
return converted
}

func getContentTypeOfFile(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()

// read the first bits of file for judgment of the mime type
buffer := make([]byte, bytesToReadForMIME)
_, err = file.Read(buffer)
if err != nil && err != io.EOF {
return "", err
}

contentType := http.DetectContentType(buffer)
return contentType, nil
}

0 comments on commit ac28a2e

Please sign in to comment.