-
Notifications
You must be signed in to change notification settings - Fork 0
/
ufile.go
82 lines (74 loc) · 1.99 KB
/
ufile.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
package ufile
import (
"bytes"
"net/http"
"os"
"strconv"
"time"
// "fmt"
"bufio"
"errors"
)
// filepath:上传的文件绝对路径
// key:ufile的key,要自己保证唯一性
// bucketName: bucket name
func Upload(filepath string, key string, bucketName string) (bool, error) {
fi, err := os.Stat(filepath)
if err != nil {
return false, err
}
fileSize := string(fi.Size())
fileType := fileMimeType(filepath)
signedStr := uploadSignedStr(key, bucketName, fileType)
authorization := "UCloud " + config.PublicKey + ":" + signedStr
url := uploadUrl(key, bucketName)
file, err := os.Open(filepath)
defer file.Close()
if err != nil {
return false, err
}
client := &http.Client{}
req, err := http.NewRequest("PUT", url, bufio.NewReader(file))
req.Header.Set("User-Agent", config.UserAgent)
req.Header.Set("Content-Length", fileSize)
req.Header.Set("Content-Type", fileType)
req.Header.Set("Authorization", authorization)
response, err := client.Do(req)
if err != nil {
return false, err
}
if response.StatusCode == 200 {
return true, nil
} else {
return false, errors.New("上传到ufile失败,请检查")
}
return true, nil
}
func uploadUrl(key string, bucketName string) string {
var buf bytes.Buffer
buf.WriteString("http://")
buf.WriteString(bucketName)
buf.WriteString(config.UrlSuffix)
buf.WriteString("/")
buf.WriteString(key)
return buf.String()
}
// 私有空间文件访问url
func PrivateCloudUrl(key string, bucketName string) string {
expire := config.ExpireSecond + time.Now().Unix()
expireStr := strconv.FormatInt(expire, 10)
signedStr := downloadSignedStr(key, bucketName, expireStr)
var buf bytes.Buffer
buf.WriteString("http://")
buf.WriteString(bucketName)
buf.WriteString(config.UrlSuffix)
buf.WriteString("/")
buf.WriteString(key)
buf.WriteString("?UCloudPublicKey=")
buf.WriteString(config.PublicKey)
buf.WriteString("&Expires=")
buf.WriteString(expireStr)
buf.WriteString("&Signature=")
buf.WriteString(signedStr)
return buf.String()
}