-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfileUpload.go
69 lines (54 loc) · 1.31 KB
/
fileUpload.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
package main
import (
"bytes"
"io"
"mime/multipart"
"net/http"
"os"
)
// Creates a new file upload http request with optional extra params
// Source: https://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
func createMultiFileUploadRequest(uri string, files map[string]string, rawFields map[string]string) (*http.Request, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if rawFields != nil {
// We add the raw form parameters to the request.
for key, value := range rawFields {
field, err := writer.CreateFormField(key)
if err != nil {
return nil, err
}
if _, err := field.Write([]byte(value)); err != nil {
return nil, err
}
}
}
if files != nil {
// We add the posted files to the request.
for key, path := range files {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
part, err := writer.CreateFormFile(key, path)
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
if err != nil {
return nil, err
}
}
}
err := writer.Close()
if err != nil {
return nil, err
}
request, err := http.NewRequest("POST", uri, body)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", writer.FormDataContentType())
return request, nil
}