Skip to content

Instantly share code, notes, and snippets.

@andrewmilson
Last active October 7, 2024 12:07
Show Gist options
  • Save andrewmilson/19185aab2347f6ad29f5 to your computer and use it in GitHub Desktop.
Save andrewmilson/19185aab2347f6ad29f5 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)
}
@gabrielNetto94
Copy link

thanks!

@lnstchtped
Copy link

thanks!

@Serares
Copy link

Serares commented Jan 14, 2023

Is it possible to compile this in an executable and then whenever you run that '.exe' the server will start to listen on incoming requests?

@pforpramit
Copy link

Hello, if I need to upload a zip file as form-data in POST request body, I am able to find this,

zipWriter := zip.NewWriter(buf)
zipFile, err := zipWriter.Create(fileName)

Unlike multipart.Writer, in case of zip.Writer I can't find any option to create form file in a key-value fashion.

How can I achieve this for zip as well?

@PzaThief
Copy link

Will this code use sendfile to achieve zero copy?

No It doesn't.
If you want to achieve zero copy, you can use os.pipe instead of sendfile.
sendfile is fit to tcp package so, it is hard to use with http package.
See this code snippet and benchmarks of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment