Member-only story

Go Tips & Common Mistakes

Go HTTP file upload and download

Beck Moulton
3 min readMay 4, 2024

This code implements a simple Go language HTTP service, which not only includes file upload and download functions, but also controls file size and generates new file names, etc.

  • uploadPath: Defines the storage path of the uploaded file.
  • maxUploadSize: Defines the maximum file size allowed to upload to 10MB.
package mainimport (
"fmt"
"io"
"math/rand"
"net"
"net/http"
"os"
"path"
"path/filepath"
)const (
uploadPath = "tmp"
maxUploadSize = 10 << 20 //10MB
)func main() {
listen, _ := net.Listen("tcp", ":8888") //文件上传
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
fmt.Printf("ParseMultipartForm err = %s", err)
return
} file, fileHeader, err := r.FormFile("file")
if err != nil {
fmt.Printf("FormFile err = %s", err)
return
} defer func() {
_ = file.Close()
}() if fileHeader.Size > maxUploadSize {
fmt.Printf("max err = %s", err)
return
} fileBytes, err := io.ReadAll(file)
if err != nil {
fmt.Printf("read err = %s", err)
return
} newFileName := randToken(12) + path.Ext(fileHeader.Filename) //新文件名+后缀
newFile, err := os.Create(filepath.Join(uploadPath, newFileName))
if err != nil {
fmt.Printf("Create err = %s", err)
return
} defer func() {
_ = newFile.Close()
}() if _, err := newFile.Write(fileBytes); err != nil || newFile.Close() != nil {
fmt.Printf("Write err = %s", err)…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)