Mercurial > gemma
comparison pkg/misc/http.go @ 2194:4d6979dedb11
Imports: Deduplicted file upload code.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Tue, 12 Feb 2019 11:09:55 +0100 |
parents | |
children | 9cbed444b8a4 |
comparison
equal
deleted
inserted
replaced
2193:35c56ace42b9 | 2194:4d6979dedb11 |
---|---|
1 // This is Free Software under GNU Affero General Public License v >= 3.0 | |
2 // without warranty, see README.md and license for details. | |
3 // | |
4 // SPDX-License-Identifier: AGPL-3.0-or-later | |
5 // License-Filename: LICENSES/AGPL-3.0.txt | |
6 // | |
7 // Copyright (C) 2018 by via donau | |
8 // – Österreichische Wasserstraßen-Gesellschaft mbH | |
9 // Software engineering by Intevation GmbH | |
10 // | |
11 // Author(s): | |
12 // * Sascha L. Teichmann <sascha.teichmann@intevation.de> | |
13 | |
14 package misc | |
15 | |
16 import ( | |
17 "bufio" | |
18 "io" | |
19 "io/ioutil" | |
20 "net/http" | |
21 "os" | |
22 "path/filepath" | |
23 | |
24 "gemma.intevation.de/gemma/pkg/config" | |
25 ) | |
26 | |
27 func StoreUploadedFile(req *http.Request, field, fname string, maxSize int64) (string, error) { | |
28 | |
29 // Check for direct upload. | |
30 f, _, err := req.FormFile(field) | |
31 if err != nil { | |
32 return "", err | |
33 } | |
34 defer f.Close() | |
35 | |
36 dir, err := ioutil.TempDir(config.TmpDir(), field) | |
37 if err != nil { | |
38 return "", err | |
39 } | |
40 | |
41 o, err := os.Create(filepath.Join(dir, fname)) | |
42 if err != nil { | |
43 os.RemoveAll(dir) | |
44 return "", err | |
45 } | |
46 | |
47 out := bufio.NewWriter(o) | |
48 | |
49 if _, err = io.Copy(out, io.LimitReader(f, maxSize)); err != nil { | |
50 o.Close() | |
51 os.RemoveAll(dir) | |
52 return "", err | |
53 } | |
54 | |
55 if err = out.Flush(); err != nil { | |
56 o.Close() | |
57 os.RemoveAll(dir) | |
58 return "", err | |
59 } | |
60 | |
61 return dir, nil | |
62 } |