1. 文件上传

  1. package main
  2. import (
  3. "io"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "github.com/julienschmidt/httprouter"
  8. )
  9. const (
  10. MAX_UPLOAD_SIZE = 1024 * 1024 * 20 //50MB
  11. )
  12. func main() {
  13. r := RegisterHandlers()
  14. http.ListenAndServe(":8080", r)
  15. }
  16. //RegisterHandlers ...
  17. func RegisterHandlers() *httprouter.Router {
  18. router := httprouter.New()
  19. router.POST("/upload", uploadHandler)
  20. return router
  21. }
  22. func uploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
  23. r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)
  24. if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
  25. log.Printf("File is too big")
  26. return
  27. }
  28. file, headers, err := r.FormFile("file")
  29. if err != nil {
  30. log.Printf("Error when try to get file: %v", err)
  31. return
  32. }
  33. //获取上传文件的类型
  34. if headers.Header.Get("Content-Type") != "image/png" {
  35. log.Printf("只允许上传png图片")
  36. return
  37. }
  38. data, err := ioutil.ReadAll(file)
  39. if err != nil {
  40. log.Printf("Read file error: %v", err)
  41. return
  42. }
  43. fn := headers.Filename
  44. err = ioutil.WriteFile("./video/"+fn, data, 0666)
  45. if err != nil {
  46. log.Printf("Write file error: %v", err)
  47. return
  48. }
  49. w.WriteHeader(http.StatusCreated)
  50. io.WriteString(w, "Uploaded successfully")
  51. }

此上传函数同样也适用于gin框架w http.ResponseWriter等同于c.Writer,r *http.Request等同于c.Request