javascriptgomux

Having trouble uploading files from Javascript and receiving it through Go


I set up a simple frontend service in JavaScript using Axios. This service takes a list of files and sends to my server code using a post request. My JavaScript looks like this

const testPost = async (files) => {
  let formData = new FormData();

  files.forEach((file) => {
    formData.append("file", file);
  });

  const res = await axios({
    method: "POST",
    url: baseUrl,
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });

  return res;
};

And my Go code looks like this:

func (h *SendHandler) TestPost(w http.ResponseWriter, r *http.Request) {
    //Allow CORS here By * or specific origin
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

    formdata := r.MultipartForm
    fmt.Println(formdata)
}

I think my problem lies in the body of my TestPost function in Go because I click send in my frontend code, I receive a response. In my Go function, when I print my formdata, it outputs <nil>. I want to be able to access each file in the list but I can't even access the formdata. I'm still new to both web dev and Go so there is definitely something I am misunderstanding here. Any pointers?


Solution

  • The documentation for MultipartForm says:

    MultipartForm is the parsed multipart form, including file uploads. This field is only available after ParseMultipartForm is called.

    Fix by calling ParseMultipartForm before using r.MultipartForm.

    err := r.ParseMultipartForm(maxMemory)
    if err != nil {
        http.Error(w, "Bad Request", http.StatusBadRequest)
        return
    }
    // r.MultipartForm is now set.
    fmt.Println(r.MultipartForm)  // does not print nil