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

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

Having trouble uploading files from Javascript and receiving it through Go

问题

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

  1. const testPost = async (files) => {
  2. let formData = new FormData();
  3. files.forEach((file) => {
  4. formData.append("file", file);
  5. });
  6. const res = await axios({
  7. method: "POST",
  8. url: baseUrl,
  9. data: formData,
  10. headers: {
  11. "Content-Type": "multipart/form-data",
  12. },
  13. });
  14. return res;
  15. };

我的Go代码如下:

  1. func (h *SendHandler) TestPost(w http.ResponseWriter, r *http.Request) {
  2. // 允许跨域请求
  3. w.Header().Set("Access-Control-Allow-Origin", "*")
  4. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  5. formdata := r.MultipartForm
  6. fmt.Println(formdata)
  7. }

我认为问题出在我的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

  1. const testPost = async (files) =&gt; {
  2. let formData = new FormData();
  3. files.forEach((file) =&gt; {
  4. formData.append(&quot;file&quot;, file);
  5. });
  6. const res = await axios({
  7. method: &quot;POST&quot;,
  8. url: baseUrl,
  9. data: formData,
  10. headers: {
  11. &quot;Content-Type&quot;: &quot;multipart/form-data&quot;,
  12. },
  13. });
  14. return res;
  15. };

And my Go code looks like this:

  1. func (h *SendHandler) TestPost(w http.ResponseWriter, r *http.Request) {
  2. //Allow CORS here By * or specific origin
  3. w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
  4. w.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type&quot;)
  5. formdata := r.MultipartForm
  6. fmt.Println(formdata)
  7. }

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来修复。

  1. err := r.ParseMultipartForm(maxMemory)
  2. if err != nil {
  3. http.Error(w, "Bad Request", http.StatusBadRequest)
  4. return
  5. }
  6. // 现在r.MultipartForm已设置。
  7. 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.

  1. err := r.ParseMultipartForm(maxMemory)
  2. if err != nil {
  3. http.Error(w, &quot;Bad Request&quot;, http.StatusBadRequest)
  4. return
  5. }
  6. // r.MultipartForm is now set.
  7. 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:

确定