panlei
2019-11-05 20f1fd7aed6ecc3fcd1dc811205dd3460975c3e6
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 WeedFSClient
 
import (
    "bytes"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "github.com/kirinlabs/HttpRequest"
    "time"
)
 
func UploadFile(uri string, fileName string, fileData []byte) (weedFilePath string, err error) {
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    _, err = writer.CreateFormFile("file", fileName)
    if err != nil {
        return "", err
    }
    boundary := writer.Boundary()
    //close_string := fmt.Sprintf("\r\n--%s--\r\n", boundary)
    close_buf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary))
    file := bytes.NewBuffer(fileData)
    request_reader := io.MultiReader(body, file, close_buf)
    //_, err = io.Copy(part, file)
    //writer.WriteField(key, val)
    request, err := http.NewRequest("POST", uri, request_reader)
    request.Header.Add("Content-Type", writer.FormDataContentType())
    timeout := time.Duration(5 * time.Second) //超时时间50ms
    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(request)
    if err != nil {
        fmt.Println("UploadFile client.Do(request) err:", err)
        return "", err
    }
    defer func() {
        if r := recover(); r != nil {
            fmt.Printf("panic的内容%v\n", r)
            msg := "上传图片服务器异常"
            if _, ok := r.(error); ok {
                msg = r.(error).Error()
                fmt.Println("panic--recover()得到的是error类型")
            }
            if _, ok := r.(string); ok {
                msg = r.(string)
                fmt.Println("panic--recover()得到的是string类型")
            }
            err = errors.New(msg)
        }
    }()
    defer resp.Body.Close()
    {
        body := &bytes.Buffer{}
        _, err := body.ReadFrom(resp.Body)
        if err != nil {
            fmt.Println("UploadFile body.ReadForm(resp.Body) err:", err)
        }
 
        m := make(map[string]interface{})
        if err := json.Unmarshal([]byte(body.String()), &m); err != nil {
            return "", err
        }
        filePath := m["fileUrl"].(string)
        return filePath,nil
    }
}
 
// 获得一个fid
 
func GetFid(url string)(weedPath string ,err error) {
    res,err := HttpRequest.NewRequest().Post(url)
    if err != nil {
        fmt.Println("网络传输错误!")
    }
    var m map[string]interface{}
    err = res.Json(&m)
    if err != nil {
        return "",err
    }
    return "http://"+m["url"].(string)+"/"+m["fid"].(string),err
}