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

@@ -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)