gitee.com/h79/goutils@v1.22.10/common/http/upload.go (about)

     1  package http
     2  
     3  import (
     4  	"bytes"
     5  	"mime/multipart"
     6  	"net/http"
     7  )
     8  
     9  func Upload(url string, filename string, headerFunc HeaderFunc) ([]byte, error) {
    10  	return UploadV2(url, &FileForm{Value: filename, Field: "file"}, headerFunc)
    11  }
    12  
    13  func UploadV2(url string, form Form, headerFunc HeaderFunc) ([]byte, error) {
    14  
    15  	var b bytes.Buffer
    16  	w := multipart.NewWriter(&b)
    17  
    18  	err := form.CreateForm(w)
    19  	if err != nil {
    20  		w.Close()
    21  		return nil, err
    22  	}
    23  	// need to close
    24  	w.Close()
    25  
    26  	hp := &Http{}
    27  	return hp.Do("POST", url, &b, func(h *http.Header) {
    28  		// Don't forget to set the content type, this will contain the boundary.
    29  		if headerFunc != nil {
    30  			headerFunc(h)
    31  		}
    32  		h.Set(KContentType, w.FormDataContentType())
    33  	})
    34  }