1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
3
4package context
5
6import (
7 "io"
8 "net/http"
9 "strings"
10)
11
12// UploadStream returns the request body or the first form file
13// Only form files need to get closed.
14func (ctx *Context) UploadStream() (rd io.ReadCloser, needToClose bool, err error) {
15 contentType := strings.ToLower(ctx.Req.Header.Get("Content-Type"))
16 if strings.HasPrefix(contentType, "application/x-www-form-urlencoded") || strings.HasPrefix(contentType, "multipart/form-data") {
17 if err := ctx.Req.ParseMultipartForm(32 << 20); err != nil {
18 return nil, false, err
19 }
20 if ctx.Req.MultipartForm.File == nil {
21 return nil, false, http.ErrMissingFile
22 }
23 for _, files := range ctx.Req.MultipartForm.File {
24 if len(files) > 0 {
25 r, err := files[0].Open()
26 return r, true, err
27 }
28 }
29 return nil, false, http.ErrMissingFile
30 }
31 return ctx.Req.Body, false, nil
32}