feat: support to infer file mime type

This commit is contained in:
buyuxiang
2022-07-18 18:40:42 +08:00
parent ddb0f26138
commit e82b1e253b
2 changed files with 19 additions and 2 deletions

View File

@@ -1,10 +1,12 @@
# Release History
## v4.1.7 (2022-07-11)
## v4.1.7 (2022-07-18)
**go version**
- fix: using '@FILEPATH' to indicate the path of the file
- feat: support indicating type and filename when uploading file
- feat: support to infer MIME type of the file automatically
## v4.1.6 (2022-07-04)

View File

@@ -7,6 +7,7 @@ import (
"fmt"
"math"
"math/rand"
"mime"
"mime/multipart"
"net/textproto"
"os"
@@ -118,7 +119,7 @@ func (w *TFormDataWriter) writeCustomFile(formKey, formValue, formType, formFile
}
if formType == "" {
formType = "application/octet-stream"
formType = inferFormType(formValue)
}
if formFileName == "" {
formFileName = filepath.Base(formValue)
@@ -137,6 +138,20 @@ func (w *TFormDataWriter) writeCustomFile(formKey, formValue, formType, formFile
return err
}
func inferFormType(formValue string) string {
extName := filepath.Ext(formValue)
formType := mime.TypeByExtension(extName)
if formType == "" {
// file without extension name
return "application/octet-stream"
}
if strings.HasPrefix(formType, "text") {
// text/... types have the charset parameter set to "utf-8" by default.
return strings.TrimSuffix(formType, "; charset=utf-8")
}
return formType
}
func multipartEncoder(formMap map[string]interface{}) (*TFormDataWriter, error) {
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)