yhirose / cpp-httplib

A C++ header-only HTTP/HTTPS server and client library
MIT License
12.91k stars 2.28k forks source link

A better way of accessing form fields #1578

Open bigbao9494 opened 1 year ago

bigbao9494 commented 1 year ago

A better way of accessing form fields

  1. Obtain the file uploaded through FormData in the interface [&] (const Request&/ req /, Response&res), and add some additional parameters, it's file_and_param.
  2. Golang has a similar processing interface that handles this issue well. All parameters are in req.params (just read directly), and all files are in req.files. req_test.zip
PixlRainbow commented 1 year ago

I would suggest that

  1. req.params be renamed to req.form.fields to make it clear that both multipart and urlencoded text fields are now accessed from the same interface. File or binary attachments would be accessed through req.form.files.
  2. Form parsing (server side) and form encoding (client side) would be delegated to a class Form with subclasses to handle the url encoded and multipart cases.
  3. We don't copy golang http heuristics for determining whether a multipart field is a file attachment, but instead take a more adaptive approach like python urllib3
bigbao9494 commented 1 year ago

This is the usage method in Golang, you can refer to it:

func upload_file(writer http.ResponseWriter, request *http.Request) {

//only FormData
if len(r.MultipartForm.Value) > 0 {
    fmt.Println(r.MultipartForm.Value["hello"])
    fmt.Println(r.MultipartForm.Value["post"])
}
//FormData and URLData
if len(request.Form) > 0 {
    for key, val := range request.Form {
        fmt.Println(key, val, reflect.TypeOf(val))
    }
}

filename := request.MultipartForm.File["file"][0].Filename
fileHeader := request.MultipartForm.File["file"][0]
file, err := fileHeader.Open()

}

yhirose commented 1 year ago

Thanks for the good suggestions!

bigbao9494 commented 1 year ago

@yhirose ,hi yhirose ,how about this featuer?

yhirose commented 1 year ago

@bigbao9494, I don't have the time to work on it right now, but I keep it as 'enhancement'. Of course, a pull request is always welcome!