/
files.go
83 lines (67 loc) · 2.1 KB
/
files.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package core
import (
"bufio"
"encoding/base64"
"fmt"
"io/ioutil"
"net/url"
"os"
)
// UploadFile - Reads a file to be uploaded and converts it to base64 to pass to the server as a response for the session
func UploadFile(file string) string {
WarningColorBold.Println("\nUploading file: " + file + "...")
// Open file on disk.
f, err := os.Open(file)
if err != nil {
ErrorColorUnderline.Println("could not read file: " + file)
return ""
}
reader := bufio.NewReader(f)
content, _ := ioutil.ReadAll(reader)
// Encode as base64.
encoded := base64.StdEncoding.EncodeToString(content)
return encoded
}
// DownloadFile - Reads a base64 encoded string and writes it out to a local file
func DownloadFile(filename string, fileb64 string) {
WarningColorBold.Println("\nDownloading file: " + filename + "...")
fileb64_url_decoded, err := url.QueryUnescape(fileb64)
if err != nil {
fmt.Println("Error decoding:", err)
return
}
file, err := base64.StdEncoding.DecodeString(fileb64_url_decoded)
if err != nil {
WarningColorBold.Println("could not base64 decode downloaded file, the raw string will be written instead...")
f, err := os.Create(filename)
if err != nil {
ErrorColorUnderline.Println("error: could not create file: " + filename)
return
}
defer f.Close()
if _, err := f.Write([]byte(fileb64)); err != nil {
ErrorColorUnderline.Println("error: could not write data to file: " + filename)
return
}
if err := f.Sync(); err != nil {
ErrorColorUnderline.Println("error: sync error, there was a problem writing data to file: " + filename)
return
}
} else {
f, err := os.Create(filename)
if err != nil {
ErrorColorUnderline.Println("error: could not create file: " + filename)
return
}
defer f.Close()
if _, err := f.Write(file); err != nil {
ErrorColorUnderline.Println("error: could not write data to file: " + filename)
return
}
if err := f.Sync(); err != nil {
ErrorColorUnderline.Println("error: sync error, there was a problem writing data to file: " + filename)
return
}
}
SuccessColorBold.Println("Downloaded file: " + filename + "!")
}