多部分请求经常用于文件上传,除了文件之外,还需要提交其他表单数据。让我们看看如何使用 Go 的 mime/multipart 和 http 包来解决这个问题。
考虑以下 HTML 表单:
<form action="/multipart" enctype="multipart/form-data" method="POST"> <label for="file">Please select a File</label> <input>
在 Go 中,我们可以按如下方式发送此多部分请求:
import ( "bytes" "io" "mime/multipart" "net/http" ) var buffer bytes.Buffer w := multipart.NewWriter(&buffer) // Write form fields w.CreateFormField("input1") w.WriteField("input1", "value1") // Prepare to write a file fd, err := os.Open("filename.dat") if err != nil { return err } // Create a form field for the file fw, err := w.CreateFormFile("file", fd.Name()) if err != nil { return err } // Copy file contents into form field if _, err := io.Copy(fw, fd); err != nil { return err } // Close writer w.Close() // Prepare request resp, err := http.Post(url, w.FormDataContentType(), &buffer) if err != nil { return err }
多部分请求发送文件的关键在于使用 *multipart.Writer 上的 CreateFormFile 创建一个专门用于文件的表单字段。创建后,我们可以使用 io.Copy 将文件内容写入此表单字段。
以上是如何使用 Go 的'multipart/form-data”发布文件和表单数据?的详细内容。更多信息请关注PHP中文网其他相关文章!