How do I POST Files and Form Data Using Go\'s `multipart/form-data`?

DDD
Release: 2024-11-25 09:48:38
Original
577 people have browsed it

How do I POST Files and Form Data Using Go's `multipart/form-data`?

POST Files in Multipart/Form-Data Request

Multipart requests are frequently used for file uploads, where along with the file, additional form data needs to be submitted. Let's look at how we can tackle this using Go's mime/multipart and http packages.

Consider the following HTML form:

<form action="/multipart" enctype="multipart/form-data" method="POST">
  <label for="file">Please select a File</label>
  <input>
Copy after login

In Go, we can send this multipart request as follows:

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
}
Copy after login

The key to sending files in multipart requests lies in using CreateFormFile on the *multipart.Writer to create a form field specifically for the file. Once created, we can use io.Copy to write the file's contents into this form field.

The above is the detailed content of How do I POST Files and Form Data Using Go\'s `multipart/form-data`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template