I am trying to pass a set of FORM values from client to server. FORM values include files, user names and other details as well.
how do i decode the file in the server side. Here i Use go lang as my server. i have created a model in my golang so that i can decode the value passed during server call.
type Details {
PhotographValue os.File `json:"photographvalue"`
AdharValue os.File `json:"adharvalue"`
userName string `json:"username"`
}
//Decoding part
var clientValues Details
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&clientValues)
In clientValues i get string data. but the file data is nil. How can i achieve this?
PS : i am not using the usual file upload method as i have other details too also, i am manipulating those details in javascript before passing on to server.
CodePudding user response:
If you pass your files as a part of multipart form you should parse it as form and use later as a separate jsons.
func handleForm(w http.ResponseWriter, req *http.Request) {
const maxAllowedSizeInBytes = 512 * 1024
err := req.ParseMultipartForm(maxAllowedSizeInBytes)
if err != nil {
// handle error here
w.WriteHeader(http.StatusBadRequest)
return
}
photographValue, _, err := req.FormFile("photographvalue")
if err != nil {
// handle error here
w.WriteHeader(http.StatusBadRequest)
return
}
adharValue, _, err := req.FormFile("adharvalue")
if err != nil {
// handle error here
w.WriteHeader(http.StatusBadRequest)
return
}
// photograph := struct{...} {}
// json.NewDecoder(file).Decode(&photograph)
// or write it to file
username := req.FormValue("username")
....
}
photographValue and adharValue conform io.Reader and you can use it to read your json file or write it to file in the system.