liuxiaolong
2019-08-16 fe514a350280f532921b644daee041f7d684343c
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
package WeedFSClient
 
import (
    "bytes"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "log"
    "mime/multipart"
    "net/http"
    "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 {
        log.Fatal(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 {
            log.Fatal(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
        //if strings.Contains(filePath,"/"){
        //    idx := strings.Index(filePath,"/")
        //    filePath = filePath[idx+1:]
        //    return filePath,nil
        //} else {
        //    return "",errors.New("file upload error")
        //}
    }
}