Skip to content

Instantly share code, notes, and snippets.

@Edmartt
Forked from andrewmilson/file-upload-multipart.go
Created January 28, 2023 01:58
Show Gist options
  • Save Edmartt/65d07eede51c7970d984187e11e30e55 to your computer and use it in GitHub Desktop.
Save Edmartt/65d07eede51c7970d984187e11e30e55 to your computer and use it in GitHub Desktop.
Golang multipart/form-data File Upload
package main
import (
"net/http"
"os"
"bytes"
"path"
"path/filepath"
"mime/multipart"
"io"
)
func main() {
fileDir, _ := os.Getwd()
fileName := "upload-file.txt"
filePath := path.Join(fileDir, fileName)
file, _ := os.Open(filePath)
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", filepath.Base(file.Name()))
io.Copy(part, file)
writer.Close()
r, _ := http.NewRequest("POST", "http://example.com", body)
r.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
client.Do(r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment