Golang GET 多部分表单数据

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>

和下面的代码

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

如何获取 "delete" 的值?

part.Header.Get("delete"))

没用

您可能可以使用 request.ParseMultipartForm 方法满足自己,然后像往常一样使用 request.FormValue 获取值。请注意,您还可以 request.MultipartForm 访问您的文件。

示例:

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("delete"))
}

该部分实现了io.Reader接口。我假设您真正要问的是如何将 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())
   } 
}