Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

multipart/form-data 中有 boundary,该怎么写? #76

Closed
Bisns opened this issue Feb 23, 2023 · 1 comment
Closed

multipart/form-data 中有 boundary,该怎么写? #76

Bisns opened this issue Feb 23, 2023 · 1 comment

Comments

@Bisns
Copy link

Bisns commented Feb 23, 2023

multipart/form-data 中有 boundary,该怎么写?

@duke-git
Copy link
Owner

multipart/form-data 中有 boundary,该怎么写?

@Bisns 使用writer.FormDataContentType 设置Content-Type header 为 multipart/form-data; boundary=xxx 。参考代码:

  • server.go
package main

import (
	"io"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/upload", handleUploadFile)
	http.ListenAndServe(":8090", nil)
}

func handleUploadFile(w http.ResponseWriter, r *http.Request) {
	log.Println("Content-Type: ", r.Header.Get("Content-Type"))

	if err := r.ParseMultipartForm(0); err != nil {
		log.Fatal(err)
		return
	}

	log.Println("FormValue(username):    ", r.FormValue("username"))
	log.Println("FormValue(password):     ", r.FormValue("password"))
	log.Println("PostFormValue(username):", r.PostFormValue("username"))
	log.Println("PostFormValue(password): ", r.PostFormValue("password"))

	// log.Println("MultipartForm: ", r.MultipartForm)

	// file, header, err := r.FormFile("file")
	// log.Println("FormFile(file): ", file, header, err)

	w.Header().Set("Content-Type", "text/json")

	io.WriteString(w, "ok")
}
  • client.go
package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"

	"github.com/duke-git/lancet/v2/netutil"
)

func main() {
	UploadFile()
}

func UploadFile() {
	file, _ := os.Open("./test.txt")
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	part, err := writer.CreateFormFile("file", filepath.Base(file.Name()))
	if err != nil {
		log.Fatal(err)
	}

	io.Copy(part, file)

	writer.WriteField("username", "test")
	writer.WriteField("password", "123456")

	err = writer.Close()
	if err != nil {
		log.Fatal(err)
	}

	header := http.Header{}
	header.Add("Content-Type", writer.FormDataContentType())

	req := &netutil.HttpRequest{
		RawURL:  "http://127.0.0.1:8090/upload",
		Method:  "POST",
		Headers: header,
		Body:    body.Bytes(),
	}

	client := netutil.NewHttpClient()

	resp, err := client.SendRequest(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	s, _ := io.ReadAll(resp.Body)

	fmt.Println("response: ", string(s)) //ok
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants