Golang multipart/form-data File Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This example is the best. Thanks!
Will this code use sendfile
to achieve zero copy
?
Спасибо)
Thank you soooooooooo much!!
thanks!! :)
alright!
Thank you
Do you have any ideas how to send a zip file using multipart writer?
Thanks!! Much appreciated!
Thanks! it's working well.
Thanks!
Thank you <3
Thanks.
Thanks
it works
it works
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!