In a web application, it's common to receive both files and JSON data in an HTTP request. To successfully process these elements, it's essential to understand how to parse them effectively.
Consider a scenario where you have an AngularJS front end that sends a request to a Go backend. The request contains a file ("file") and JSON data ("doc"). Your goal is to parse both the PDF file and the JSON data from this request.
To resolve this issue, you need to separately process both the file and JSON data. By utilizing http.(*Request).MultipartReader() and iterating over the parts using NextPart(), you can extract and parse each element.
mr, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
For each part in the multipart request:
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
If the part is a file (part.FormName() == "file"):
outfile, err := os.Create("./docs/" part.FileName())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer outfile.Close()
_, err = io.Copy(outfile, part)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
If the part contains JSON data (part.FormName() == "doc"):
jsonDecoder := json.NewDecoder(part)
err = jsonDecoder.Decode(&doc)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
After parsing both file and JSON data, you can perform any necessary post-processing, such as saving it to a database or sending a response to the client.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3