最后附上阿里云上传代码
初始化阿里云
func createOSS() (*oss.Client, error) {
client, err := oss.New(endPoint, setting.AliyunCloudConf.AccessKeyID, setting.AliyunCloudConf.AccessKeySecret,
func(c *oss.Client) {
c.Config.IsDebug = setting.IsDebug
c.Config.HTTPTimeout = oss.HTTPTimeout{
IdleConnTimeout: 90 * time.Second,
ConnectTimeout: 30 * time.Second,
ReadWriteTimeout: 60 * time.Second,
HeaderTimeout: 60 * time.Second,
LongTimeout: 300 * time.Second,
}
})
if err != nil {
err := fmt.Errorf("aliyun cloud start failed, err: %s", err.Error())
//tools.Mlog.Error(err.Error())
return nil, err
}
return client, nil
}
func PutObject(objKey string, reader io.Reader, options ...oss.Option) error {
client, err := createOSS()
if err != nil {
return err
}
bucket, err := client.Bucket(bucketName)
if err != nil {
return err
}
return bucket.PutObject(objKey, reader, options...)
}
func UploadFileWithReader(info reqUpdateWXFile) (objKey string, err error) {
intn := rand.Intn(10000)
if info.Source == aliyun.Avatar {
objKey = fmt.Sprintf("%s/%d_%d%s", aliyun.Avatar, time.Now().UTC().Unix(), intn, info.Name)
} else if info.Source == aliyun.Photo {
objKey = fmt.Sprintf("%s/%d_%d%s", aliyun.Photo, time.Now().UTC().Unix(), intn, info.Name)
} else if info.Source == aliyun.Video {
objKey = fmt.Sprintf("%s/%d_%d%s", aliyun.Video, time.Now().UTC().Unix(), intn, info.Name)
} else if info.Source == aliyun.Other {
objKey = fmt.Sprintf("%s/%d_%d%s", aliyun.Other, time.Now().UTC().Unix(), intn, info.Name)
} else {
return "", ErrSupportFileType
}
err = aliyun.PutObject(objKey, info.File, oss.ObjectACL(oss.ACLPublicRead), oss.ContentType(info.FileCategory))
if err != nil {
return "", err
}
return
}