From e82b1e253b9d8c7aa2f6e487f582a23cb5f02b0d Mon Sep 17 00:00:00 2001 From: buyuxiang <347586493@qq.com> Date: Mon, 18 Jul 2022 18:40:42 +0800 Subject: [PATCH] feat: support to infer file mime type --- docs/CHANGELOG.md | 4 +++- hrp/internal/builtin/function.go | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index f7c86eb7..2ae3127c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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) diff --git a/hrp/internal/builtin/function.go b/hrp/internal/builtin/function.go index 538c79a8..a5b3c36f 100644 --- a/hrp/internal/builtin/function.go +++ b/hrp/internal/builtin/function.go @@ -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)