Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
}
@Altiano
Copy link

Altiano commented May 14, 2020

Thanks!

@hhsm95
Copy link

hhsm95 commented Jun 2, 2020

This example is the best. Thanks!

@jingyugao
Copy link

jingyugao commented Sep 7, 2020

Will this code use sendfile to achieve zero copy?

@EvgTG
Copy link

EvgTG commented Nov 3, 2020

Спасибо)

@LIMHARRY
Copy link

LIMHARRY commented Mar 4, 2021

Thank you soooooooooo much!!

@magarem
Copy link

magarem commented May 15, 2021

thanks!! :)

@kabaluyot
Copy link

kabaluyot commented Jun 19, 2021

alright!

@irvanrahadhian
Copy link

irvanrahadhian commented Jul 30, 2021

Thank you

@yedamao
Copy link

yedamao commented Aug 6, 2021

👍

@MingyiLiang
Copy link

MingyiLiang commented Nov 2, 2021

Do you have any ideas how to send a zip file using multipart writer?

@AlfarisiN
Copy link

AlfarisiN commented Mar 18, 2022

Thanks!! Much appreciated!

@foofybuster
Copy link

foofybuster commented Apr 22, 2022

Thanks! it's working well.

@AnjanaMadu
Copy link

AnjanaMadu commented May 6, 2022

Thanks!

@lsdrfrx
Copy link

lsdrfrx commented May 12, 2022

Thank you <3

@Jontes-Tech
Copy link

Jontes-Tech commented May 24, 2022

Thanks.

@devnote-dev
Copy link

devnote-dev commented May 27, 2022

Thanks 👍

@pablodz
Copy link

pablodz commented May 31, 2022

it works

@zhangpengspin
Copy link

zhangpengspin commented May 31, 2022

it works

@Sujaybiradar25
Copy link

Sujaybiradar25 commented Jun 8, 2022

Thanks!

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