@@ -2,6 +2,7 @@ package fileupload
2
2
3
3
import (
4
4
"bytes"
5
+ "context"
5
6
"encoding/json"
6
7
"io"
7
8
"mime/multipart"
@@ -10,6 +11,7 @@ import (
10
11
"os"
11
12
"strconv"
12
13
14
+ "cloud.google.com/go/storage"
13
15
"github.com/kennygrant/sanitize"
14
16
)
15
17
@@ -18,7 +20,7 @@ type File struct {
18
20
URL string `json:"URL"`
19
21
}
20
22
21
- func FromRequest (req * http.Request , path string ) (string , string , error ) {
23
+ func FromRequestToFile (req * http.Request , path string ) (string , string , error ) {
22
24
req .ParseMultipartForm (32 )
23
25
file , handler , err := req .FormFile ("file" )
24
26
if err != nil {
@@ -41,6 +43,41 @@ func FromRequest(req *http.Request, path string) (string, string, error) {
41
43
return filename , fullpath , nil
42
44
}
43
45
46
+ func FromRequestToGoogleBucket (req * http.Request , bucketName string ) (string , string , error ) {
47
+ req .ParseMultipartForm (32 )
48
+ file , handler , err := req .FormFile ("file" )
49
+ if err != nil {
50
+ return "" , "" , err
51
+ }
52
+ defer file .Close ()
53
+
54
+ ctx := context .Background ()
55
+ client , err := storage .NewClient (ctx )
56
+ if err != nil {
57
+ // TODO: Handle error.
58
+ }
59
+ bkt := client .Bucket (bucketName )
60
+
61
+ filename := handler .Filename
62
+ // fullpath := path + filename
63
+
64
+ obj := bkt .Object (filename )
65
+ if err != nil {
66
+ return "" , "" , err
67
+ }
68
+ w := obj .NewWriter (ctx )
69
+ _ , err = io .Copy (w , file )
70
+ if err != nil {
71
+ return "" , "" , err
72
+ }
73
+
74
+ if err := w .Close (); err != nil {
75
+ return "" , "" , err
76
+ }
77
+
78
+ return filename , bucketName , nil
79
+ }
80
+
44
81
func FromBuffer (name string , path string , body io.Reader ) (string , string , error ) {
45
82
filename := getValidFileName (path , name )
46
83
fullpath := path + filename
0 commit comments