在JavaScript中上传文件并通过Go接收时遇到了问题。

huangapple go评论94阅读模式
英文:

Having trouble uploading files from Javascript and receiving it through Go

问题

我使用Axios在JavaScript中设置了一个简单的前端服务。该服务接收一个文件列表,并使用POST请求将其发送到我的服务器代码。我的JavaScript代码如下:

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;
};

我的Go代码如下:

func (h *SendHandler) TestPost(w http.ResponseWriter, r *http.Request) {
	// 允许跨域请求
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

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

我认为问题出在我的Go代码的TestPost函数的主体部分。当我在前端代码中点击发送后,我收到了一个响应。但是在我的Go函数中,当我打印formdata时,输出为<nil>。我希望能够访问列表中的每个文件,但我甚至无法访问formdata。我对Web开发和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) =&gt; {
  let formData = new FormData();

  files.forEach((file) =&gt; {
    formData.append(&quot;file&quot;, file);
  });

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

  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(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
	w.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type&quot;)

	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 &lt;nil&gt;. 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?

答案1

得分: 1

MultipartForm的文档中提到:

MultipartForm是解析后的多部分表单,包括文件上传。只有在调用ParseMultipartForm之后,该字段才可用。

通过在使用r.MultipartForm之前调用ParseMultipartForm来修复。

err := r.ParseMultipartForm(maxMemory)
if err != nil {
    http.Error(w, "Bad Request", http.StatusBadRequest)
    return
}
// 现在r.MultipartForm已设置。
fmt.Println(r.MultipartForm)  // 不会打印nil
英文:

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, &quot;Bad Request&quot;, http.StatusBadRequest)
    return
}
// r.MultipartForm is now set.
fmt.Println(r.MultipartForm)  // does not print nil

huangapple
  • 本文由 发表于 2021年9月8日 10:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/69096441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定