-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.go
228 lines (197 loc) · 6.05 KB
/
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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package main
import (
"archive/zip"
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strconv"
)
const (
uploadFormFileName = "uploadfile"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
serveUpload(w, r)
case "POST":
handleUpload(w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func serveUpload(w http.ResponseWriter, r *http.Request) {
m, err := loadFromCSVFile(globalModel.WorkingDir, globalModel.CSVFilename)
if err != nil {
globalModel.Err = fmt.Errorf("Error: could not load from CSV File: %v", err)
} else {
globalModel = m
}
render(w, uploadTmpl, globalModel)
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
m, err := loadFromCSVFile(globalModel.WorkingDir, globalModel.CSVFilename)
if err != nil {
globalModel.Err = fmt.Errorf("Error: could not load from CSV File: %v", err)
} else {
globalModel = m
}
uploadFiles, err := readUploadFiles(globalModel)
if err != nil {
//http.Error(w, fmt.Sprintf("Failed to read upload files: %v", err), http.StatusInternalServerError)
globalModel.Err = fmt.Errorf("Failed to read upload files: %v", err)
render(w, uploadTmpl, globalModel)
return
}
workingDirBase := filepath.Base(globalModel.WorkingDir)
zipFilename := filepath.Join(globalModel.WorkingDir, workingDirBase+".zip")
if err := zipFiles(uploadFiles, zipFilename, workingDirBase); err != nil {
//http.Error(w, fmt.Sprintf("Failed to zip files: %v", err), http.StatusInternalServerError)
globalModel.Err = fmt.Errorf("Failed to zip files: %v", err)
render(w, uploadTmpl, globalModel)
return
}
username := r.PostFormValue("username")
password := r.PostFormValue("password")
remain, err := postFile(zipFilename, *uploadURL, uploadFormFileName, username, password)
if err != nil {
//http.Error(w, fmt.Sprintf("Failed to upload zip file: %v", err), http.StatusInternalServerError)
globalModel.Err = fmt.Errorf("Failed to upload zip file: %v", err)
render(w, uploadTmpl, globalModel)
return
}
globalModel.Success = fmt.Sprintf("Upload was successful! (%v MB remain)", remain/1024/1024)
render(w, uploadTmpl, globalModel)
}
type uploadFile struct {
Name string
Body []byte
Info os.FileInfo
}
func readUploadFiles(model *model) ([]*uploadFile, error) {
var uploadFiles []*uploadFile
csvFile := filepath.Join(model.WorkingDir, model.CSVFilename)
csvBody, err := ioutil.ReadFile(csvFile)
if err != nil {
return nil, fmt.Errorf("read csv file: %v", err)
}
info, err := os.Stat(csvFile)
if err != nil {
return nil, fmt.Errorf("stat csv file: %v", err)
}
uploadFiles = append(uploadFiles, &uploadFile{Name: model.CSVFilename, Body: csvBody, Info: info})
for _, img := range model.Images {
imgFile := filepath.Join(model.WorkingDir, img.Name)
imgBody, err := ioutil.ReadFile(imgFile)
if err != nil {
return nil, fmt.Errorf("read img file: %v", err)
}
info, err := os.Stat(imgFile)
if err != nil {
return nil, fmt.Errorf("stat img file: %v", err)
}
uploadFiles = append(uploadFiles, &uploadFile{Name: img.Name, Body: imgBody, Info: info})
}
return uploadFiles, nil
}
func zipFiles(uploadFiles []*uploadFile, zipFilename, dirName string) error {
zipFile, err := os.Create(zipFilename)
if err != nil {
return err
}
defer func() {
if cerr := zipFile.Close(); err == nil {
err = cerr
}
}()
zw := zip.NewWriter(zipFile)
for _, file := range uploadFiles {
header, ierr := zip.FileInfoHeader(file.Info)
if ierr != nil {
return fmt.Errorf("file info header: %v", ierr)
}
// Putting the files under a directory.
header.Name = filepath.Join(dirName, header.Name)
hw, herr := zw.CreateHeader(header)
if herr != nil {
return fmt.Errorf("create header: %v", herr)
}
_, err = hw.Write(file.Body)
if err != nil {
return fmt.Errorf("write zip file: %v", err)
}
}
if err = zw.Close(); err != nil {
return fmt.Errorf("close zip archive: %v", err)
}
return err
}
func postFile(filename, targetURL, formName, username, password string) (int64, error) {
buf := &bytes.Buffer{}
mw := multipart.NewWriter(buf)
// this step is very important
formFile, err := mw.CreateFormFile(formName, filename)
if err != nil {
return 0, fmt.Errorf("error creating form file: %v", err)
}
f, err := os.Open(filename)
if err != nil {
return 0, fmt.Errorf("error opening upload file: %v", err)
}
_, err = io.Copy(formFile, f)
if err != nil {
return 0, fmt.Errorf("error copying to form file: %v", err)
}
// Add the other fields
// username
if formFile, err = mw.CreateFormField("username"); err != nil {
return 0, fmt.Errorf("error creating form field username: %v", err)
}
if _, err = formFile.Write([]byte(username)); err != nil {
return 0, fmt.Errorf("error writing value for form field username: %v", err)
}
// password
if formFile, err = mw.CreateFormField("password"); err != nil {
return 0, fmt.Errorf("error creating form field password: %v", err)
}
if _, err = formFile.Write([]byte(password)); err != nil {
return 0, fmt.Errorf("error writing value for form field password: %v", err)
}
if err = mw.Close(); err != nil {
return 0, fmt.Errorf("error closing multipart writer: %v", err)
}
contentType := mw.FormDataContentType()
resp, err := http.Post(targetURL, contentType, buf)
if err != nil {
if resp != nil {
return 0, fmt.Errorf("%v %v: %d %v", resp.Request.Method, resp.Request.URL, resp.StatusCode, err)
}
return 0, err
}
defer func() {
if cerr := resp.Body.Close(); cerr == nil {
err = cerr
}
}()
data, rerr := ioutil.ReadAll(resp.Body)
if rerr != nil {
return 0, fmt.Errorf("error reading response body: %v", rerr)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return 0, fmt.Errorf("%v %v: %d %s", resp.Request.Method, resp.Request.URL, resp.StatusCode, string(data))
}
var remain int64
body := string(data)
if resp.StatusCode == 200 {
rem, err := strconv.ParseInt(body, 10, 64)
if err != nil {
return 0, fmt.Errorf("expected response body to be an integer, got: %v", body)
}
remain = rem
}
return remain, err
}