Skip to content

Commit bc2fd64

Browse files
committed
filename from req
1 parent 69dc939 commit bc2fd64

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

fileupload.go

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package fileupload
22

33
import (
44
"bytes"
5+
"context"
56
"encoding/json"
67
"io"
78
"mime/multipart"
@@ -10,6 +11,7 @@ import (
1011
"os"
1112
"strconv"
1213

14+
"cloud.google.com/go/storage"
1315
"github.com/kennygrant/sanitize"
1416
)
1517

@@ -18,7 +20,7 @@ type File struct {
1820
URL string `json:"URL"`
1921
}
2022

21-
func FromRequest(req *http.Request, path string) (string, string, error) {
23+
func FromRequestToFile(req *http.Request, path string) (string, string, error) {
2224
req.ParseMultipartForm(32)
2325
file, handler, err := req.FormFile("file")
2426
if err != nil {
@@ -41,6 +43,41 @@ func FromRequest(req *http.Request, path string) (string, string, error) {
4143
return filename, fullpath, nil
4244
}
4345

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+
4481
func FromBuffer(name string, path string, body io.Reader) (string, string, error) {
4582
filename := getValidFileName(path, name)
4683
fullpath := path + filename

0 commit comments

Comments
 (0)