Browse Source

解决图片上传问题

dcsunny 4 years ago
parent
commit
2c763ee33d
1 changed files with 45 additions and 2 deletions
  1. 45 2
      http/handle.go

+ 45 - 2
http/handle.go

@@ -1,15 +1,17 @@
 package http
 
 import (
+	"bytes"
+	json2 "encoding/json"
 	"io/ioutil"
 	"net/http"
 	"strings"
 
-	"github.com/go-kratos/kratos/v2/transport/http/binding"
 	"google.golang.org/protobuf/types/known/emptypb"
 
 	"github.com/go-kratos/kratos/v2/encoding"
 	"github.com/go-kratos/kratos/v2/errors"
+	"github.com/go-kratos/kratos/v2/transport/http/binding"
 
 	"git.ikuban.com/server/kratos-utils/http/encoding/json"
 	_ "github.com/go-kratos/kratos/v2/encoding/proto"
@@ -19,10 +21,14 @@ import (
 func DecodeRequest(req *http.Request, v interface{}) error {
 	method := strings.ToUpper(req.Method)
 	if method == "POST" || method == "PUT" || method == "DELETE" {
+		contextType := req.Header.Get(ContentTypeHeader)
+		if strings.HasPrefix(contextType, "multipart/form-data") {
+			return parseForm(req, v)
+		}
 		if _, ok := v.(*emptypb.Empty); ok {
 			return binding.BindForm(req, v)
 		}
-		subtype := contentSubtype(req.Header.Get(ContentTypeHeader))
+		subtype := contentSubtype(contextType)
 		if codec := encoding.GetCodec(subtype); codec != nil {
 			data, err := ioutil.ReadAll(req.Body)
 			if err != nil {
@@ -34,6 +40,43 @@ func DecodeRequest(req *http.Request, v interface{}) error {
 	return binding.BindForm(req, v)
 }
 
+func parseForm(req *http.Request, v interface{}) error {
+	err := req.ParseMultipartForm(102400000)
+	if err != nil {
+		return err
+	}
+	if req.MultipartForm == nil {
+		return nil
+	}
+	value := make(map[string]interface{})
+	if req.MultipartForm.File != nil {
+		for k1, v1 := range req.MultipartForm.File {
+			f, err := v1[0].Open()
+			if err != nil {
+				return err
+			}
+			var buf bytes.Buffer
+			_, err = buf.ReadFrom(f)
+			if err != nil {
+				return err
+			}
+			value[k1] = buf.Bytes()
+			value[k1+"Filename"] = v1[0].Filename
+		}
+	}
+	if req.MultipartForm.Value != nil {
+		for k1, v1 := range req.MultipartForm.Value {
+			value[k1] = v1
+		}
+	}
+	j, err := json2.Marshal(value)
+	if err != nil {
+		return err
+	}
+	err = json2.Unmarshal(j, v)
+	return err
+}
+
 // encodeResponse encodes the object to the HTTP response.
 func EncodeResponse(w http.ResponseWriter, r *http.Request, v interface{}) error {
 	codec := codecForRequest(r)