-
-
Notifications
You must be signed in to change notification settings - Fork 393
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
Comments
@Bisns 使用writer.FormDataContentType 设置
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")
}
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
} |
Closed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
multipart/form-data 中有 boundary,该怎么写?
The text was updated successfully, but these errors were encountered: