// UploadFile 文件上传函数
func UploadFile(c *gin.Context) {
path := c.Param("path")
if !isAllow(path) { // 是否在允许的路径
c.Status(404)
return
}
// 获取请求用户主键
str, isExists := c.Get("userID")
if !isExists {
c.JSON(Status.JWTErr, R(Status.JWTErr, nil, "中间件异常!"))
return
}
userID := str.(uint)
// 文件类型,默认为jpg
typ := c.GetHeader("type")
if typ == "" {
typ = "jpg"
}
// 对象的键命名规则
key := fmt.Sprintf("%s-%s-%s-%s.%s",
path, // 照片的类别,attend、activity ...
strconv.FormatUint(uint64(userID), 10), // 用户的主键
time.Now().Format("2006-01-02_15h04m05s"), // 时间戳的格式化,精确到秒
Util.RandStr(5), // 随机字符串
typ) // 文件类型
// 创建obs请求
input := new(obs.PutObjectInput)
input.Bucket = obsCfg.ImgBucket
input.Key = key
input.Body = c.Request.Body
output, e := client.PutObject(input)
if e != nil || output.StatusCode != 200 {
c.JSON(Status.UploadFail, R(Status.UploadFail, nil, "文件对象上传失败!"+e.Error()))
return
}
c.JSON(Status.OK, R(Status.OK, key, "上传成功!"))
}
【Go Web】Go对接华为云obs代码
最新推荐文章于 2024-05-16 10:39:28 发布