Home > Software engineering >  Parsing POST request body containing file content
Parsing POST request body containing file content

Time:01-06

I compose an HTTP request to send file content:

// HTTP request.
req, err := UploadRequest("/slice", "file", pth)

By this function:

// Creates a new file upload http request.
// https://gist.github.com/mattetti/5914158/f4d1393d83ebedc682a3c8e7bdc6b49670083b84
func UploadRequest(uri string, paramName, path string) (*http.Request, error) {
    file, err := os.Open(path) // handle err...
    fileContents, err := ioutil.ReadAll(file) // handle err...
    fi, err := file.Stat() // handle err...
    file.Close()

    body := new(bytes.Buffer)
    writer := multipart.NewWriter(body)
    part, err := writer.CreateFormFile(paramName, fi.Name()) // handle err...
    part.Write(fileContents)

    err = writer.Close() // handle err...

    request, err := http.NewRequest("POST", uri, body)
    request.Header.Add("Content-Type", writer.FormDataContentType())
    return request, err
}

Question

The request handler receives the request body:

func Handler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        body, err := ioutil.ReadAll(r.Body) // I have request body :)
    }
}

Debugger shows the request body is:

enter image description here

I'm trying to get the body data after \r\n\r\n characters. How can I do that?

Tried

This is tried, but didn't work:

err = r.ParseForm() // Handle err...
stl := r.PostForm.Get("file") // "file" param name is hard-coded.

// `stl` is just an empty string.

CodePudding user response:

Use Request.FormFile to parse the multipart request body and return the file within:

func Handler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        f, h, err := r.FormFile(paramName)
        if err != nil {
            // TODO: Handle error
        }
        data, err := ioutil.ReadAll(f)
        if err != nil {
            // TODO: Handle error
        }
    }
}
  •  Tags:  
  • Related