-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.go
38 lines (33 loc) · 814 Bytes
/
upload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package drive
import (
"mime"
"os"
"path/filepath"
"github.com/pkg/errors"
"google.golang.org/api/drive/v3"
)
// Upload uploads file to google drive.
func (s *Service) Upload(filePath string) (*drive.File, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, errors.New("file does not exist " + filePath)
}
defer func() { _ = f.Close() }()
_, fileName := filepath.Split(f.Name())
tp := getFilePathMimeType(filePath)
df := &drive.File{
MimeType: tp,
Name: fileName,
Parents: []string{"root"},
}
file, err := s.drive.Files.Create(df).Media(f).Do()
if err != nil {
return nil, errors.Wrap(err, "could not create file")
}
return file, nil
}
func getFilePathMimeType(filePath string) string {
ext := filepath.Ext(filePath)
tp := mime.TypeByExtension(ext)
return tp
}