【Go Web】Go对接华为云obs代码

// 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, "上传成功!"))
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值