Golang获取multipart form-data的GET请求

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

Golang GET multipart form-data

问题

假设我有一个HTML表单:

<form enctype="multipart/form-data" action="http://localhost:8080/incarcat" method="post">
    <input type="file" name="file" multiple="multiple"/>
    <input type="checkbox" name="delete" value="delete">
    <input type="submit" value="Load" />
</form>

以及以下Go代码:

read_form, err := req.MultipartReader()
for {
    part, err_part := read_form.NextPart()
    if err_part == io.EOF {
        break
    }
    if part.FormName() == "file" {
        // 处理文件
    } else if part.FormName() == "delete" {
        // 清除文件夹
        log.Println("delete is: ", part.Header.Get("delete"))
    }
}

如何获取"delete"的值?

part.Header.Get("delete")这样写是不起作用的。

英文:

Let say I have a html form

&lt;form enctype=&quot;multipart/form-data&quot; action=&quot;http://localhost:8080/incarcat&quot; method=&quot;post&quot;&gt;
	&lt;input type=&quot;file&quot; name=&quot;file&quot; multiple=&quot;multiple&quot;/&gt;
	&lt;input type=&quot;checkbox&quot; name=&quot;delete&quot; value=&quot;delete&quot;&gt;
	&lt;input type=&quot;submit&quot; value=&quot;Load&quot; /&gt;
&lt;/form&gt;

and the following go code

read_form, err := req.MultipartReader()
for {
	part, err_part := read_form.NextPart()
	if err_part == io.EOF {
		break
	}
	if part.FormName() == &quot;file&quot; {
		//do something with files
	} else if part.FormName() == &quot;delete&quot; {
		//curata_folder()
		log.Println(&quot;delete is: &quot;, part.Header.Get(&quot;delete&quot;))
	}
}

How do i get the value of "delete"?

part.Header.Get(&quot;delete&quot;))

it's not working

答案1

得分: 17

该部分实现了io.Reader接口。我假设你真正想问的是如何将该部分的读取器转换为字符串,假设它不是一个文件。你可以像这样做:

for {
   part, err_part := read_form.NextPart()
   if err_part == io.EOF {
      break
   }
   if part.FormName() == "delete" {
      buf := new(bytes.Buffer)
      buf.ReadFrom(part)
      log.Println("delete is: ", buf.String())
   } 
}
英文:

The part implements the io.Reader interface. I am assuming what you are really asking is how to convert the part reader into a string, in the case that it is not a file. You can do so like this:

for {
   part, err_part := read_form.NextPart()
   if err_part == io.EOF {
      break
   }
   if part.FormName() == &quot;delete&quot; {
      buf := new(bytes.Buffer)
      buf.ReadFrom(part)
      log.Println(&quot;delete is: &quot;, buf.String())
   } 
}

答案2

得分: 15

你可以使用request.ParseMultipartForm方法来解析多部分表单,然后像往常一样使用request.FormValue来获取值。请注意,你还可以使用request.MultipartForm来访问文件。

示例:

func(w http.ResponseWriter, r *http.Request) {
    // 这里的参数是应该加载到内存中的表单数据的大小,剩余的数据会被放在临时文件中
    r.ParseMultipartForm(0)
    
    fmt.Println(r.FormValue("delete"))
}
英文:

You can probably content yourself by using the request.ParseMultipartForm method, then use the request.FormValue to get values as usual. Note that you also have the request.MultipartForm to get access to your files.

Example:

func(w http.ResponseWriter, r *http.Request) {
	// Here the parameter is the size of the form data that should
	// be loaded in memory, the remaining being put in temporary
	// files
	r.ParseMultipartForm(0)
	
	fmt.Println(r.FormValue(&quot;delete&quot;))
}

答案3

得分: 0

以下是如何处理 multipart/form-data 并使用 Golang 从 HTTP 请求创建文件的示例。
此外,可以在这里查看如何进行单元测试 Golang获取multipart form-data的GET请求

func UploadFile(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseMultipartForm(4); err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    // 创建临时目录
    dir, err := os.MkdirTemp("", "tmp")
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }

    // 创建临时文件
    f, err := os.CreateTemp(dir, "")
    if err != nil {
        _ = os.RemoveAll(dir)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    defer closeFile(f)
    defer os.RemoveAll(dir)

    code := doSomething(f)
    if code != http.StatusOK {
        w.WriteHeader(code)
        return
    }

    w.WriteHeader(http.StatusCreated)
    w.Write([]byte("Done :)"))
}
英文:

The follow is an example of how to handle multipart/form-data and create a file from HTTP request using Golang.
Also, take a look in here for how to unit-test it Golang获取multipart form-data的GET请求

func UploadFile(w http.ResponseWriter, r *http.Request) {
 if err := r.ParseMultipartForm(4); err != nil {
  w.WriteHeader(http.StatusBadRequest)
  return
 }

 // create a temporary directory
 dir, err := os.MkdirTemp(&quot;&quot;, &quot;tmp&quot;)
 if err != nil {
  w.WriteHeader(http.StatusInternalServerError)
  return
 }

 // create a temporary file
 f, err := os.CreateTemp(dir, &quot;&quot;)
 if err != nil {
  _ = os.RemoveAll(dir)
  w.WriteHeader(http.StatusInternalServerError)
  return
 }
 defer closeFile(f)
 defer os.RemoveAll(dir)

 code := doSomething(f)
 if code != http.StatusOK {
  w.WriteHeader(code)
  return
 }

 w.WriteHeader(http.StatusCreated)
 w.Write([]byte(&quot;Done :)&quot;))
}

huangapple
  • 本文由 发表于 2015年3月9日 18:42:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/28940005.html
匿名

发表评论

匿名网友

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

确定