在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
package main import ( "fmt" "io" "io/ioutil" "log" "net/http" "github.com/julienschmidt/httprouter" ) const ( MAX_UPLOAD_SIZE = 1024 * 1024 * 20 //20MB ) func main() { r := RegisterHandlers() http.ListenAndServe(":8080", r) } //RegisterHandlers ... func RegisterHandlers() *httprouter.Router { router := httprouter.New() router.POST("/upload", uploadHandler) return router } func uploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) { r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE) if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil { log.Printf("File is too big") return } file, headers, err := r.FormFile("file") if err != nil { log.Printf("Error when try to get file: %v", err) return } fmt.Println(headers.Header.Get("Content-Type")) //获取上传文件的类型 if headers.Header.Get("Content-Type") != "image/jpeg" { log.Printf("只允许上传jpeg图片") return } data, err := ioutil.ReadAll(file) if err != nil { log.Printf("Read file error: %v", err) return } fn := headers.Filename err = ioutil.WriteFile("./"+fn, data, 0777) if err != nil { log.Printf("Write file error: %v", err) return } w.WriteHeader(http.StatusCreated) io.WriteString(w, "Uploaded successfully") }
上传文件流程 |
请发表评论