/
FormPost.go
67 lines (51 loc) · 2.06 KB
/
FormPost.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
package tools
import (
"auxpi/auxpiAll"
"bytes"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
)
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
//自定义 post 表单上传
func FormPost(fileContent *auxpi.FormFile, url string, header map[string]string) string {
body := new(bytes.Buffer)
w := multipart.NewWriter(body)
contentType := w.FormDataContentType()
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
escapeQuotes(fileContent.Key), escapeQuotes(fileContent.Name)))
h.Set("Content-Type", "application/"+fileContent.Type)
file, _ := w.CreatePart(h)
file.Write(fileContent.Value)
w.Close()
req, _ := http.NewRequest("POST", url, body)
req.Header.Set("Content-Type", contentType)
if len(header) > 0 {
for k, v := range header {
req.Header.Add(k, v)
}
}
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
return string(data)
}
func AliFormPost(fileContent *auxpi.FormFile, url string) string {
payload := strings.NewReader("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + fileContent.Name + "\"\r\nContent-Type: " + fileContent.Type + "\r\n\r\n" + string(fileContent.Value) + "\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"scene\"\r\n\r\naeMessageCenterV2ImageRule\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\n" + fileContent.Name + "\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("cache-control", "no-cache")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return string(body)
}