Exemple #1
0
func (h *Handler) Handle(req zerver.Request, resp zerver.Response) {
	req.Wrap(func(req *http.Request, shouldClose bool) (r *http.Request, c bool) {
		r, c = req, shouldClose

		err := req.ParseMultipartForm(h.MaxMemory)
		if err != nil {
			handle.SendErr(resp, handle.BadRequest(err))
			return
		}

		if req.MultipartForm == nil || req.MultipartForm.File == nil {
			handle.SendErr(resp, h.ErrNoFile)
			return
		}

		files, has := req.MultipartForm.File[h.FileKey]
		if !has || len(files) == 0 {
			handle.SendErr(resp, h.ErrNoFile)
			return
		}

		file := convertFileHandler(files[0])
		if !h.isSuffixSupported(filepath.Ext(file.Filename)) {
			handle.SendErr(resp, h.ErrNonImage)
			return
		}

		if file.Size() > h.MaxSize {
			handle.SendErr(resp, h.ErrTooLarge)
			return
		}

		fd, err := file.Open()
		if err != nil {
			handle.SendErr(resp, handle.BadRequest(err))
			return
		}

		defer fd.Close()
		path, err := h.SaveImage(fd)
		if err != nil {
			handle.SendErr(resp, err)
			return
		}

		resp.Send(h.PathKey, path)
		return
	})
}