4

GO项目实战—开发上传图片功能

 1 year ago
source link: https://studygolang.com/articles/35673
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

GO项目实战—开发上传图片功能

qiaoshuai951123 · 大约14小时之前 · 202 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览    

goshop开源项目的更新

备注:前面项目中用到的代码已经分享到GitHub中去了,并且以后所有项目中会出现的代码都会提交上去,欢迎查阅。

地址 goshop 感兴趣的可以点个star哦~

https://gitee.com/jobhandsome/goshop/

今天图片上传功能,下面是技术点:

  1. 限制图片上传的类型:jpg|png|jpeg
  2. 保存图片并以时间(天)作为动态目录存储接下来咱们就来实现以上功能

接下来咱们就来实现以上功能:

// 上传图片接口
func Uploads(ctx *gin.Context) {
  //1、获取上传的文件
  file, err := ctx.FormFile("file")
  if err == nil {
    //2、获取后缀名 判断类型是否正确 .jpg .png .gif .jpeg
    extName := path.Ext(file.Filename)
    allowExtMap := map[string]bool{
      ".jpg":  true,
      ".png":  true,
      ".jpeg": true,
    }
    if _, ok := allowExtMap[extName]; !ok {
      logger.PanicError(errors.New("文件类型不合法"), "上传错误", false)
      // 返回值
      utils.Fail(ctx, "文件类型不合法", nil)
      return
    }
    //3、创建图片保存目录,linux下需要设置权限(0755可读可写) uploads/20200623
    currentTime := time.Now().Format("20060102")
    // 使用flag 定义路径字符变量
    dir := flag.String("uploads", "./uploads/"+currentTime, "file name")
    // 生成目录文件夹,并错误判断
    if err := os.MkdirAll(*dir, 0755); err != nil {
      logger.PanicError(err, "上传错误", false)
      // 返回值
      utils.Fail(ctx, "MkdirAll失败", nil)
      return
    }
    //4、生成文件名称 144325235235.png
    fileUnixName := strconv.FormatInt(time.Now().UnixNano(), 10)
    //5、上传文件 static/upload/20200623/144325235235.png
    saveDir := path.Join(*dir, fileUnixName+extName)
    err := ctx.SaveUploadedFile(file, saveDir)
    if err != nil {
      logger.PanicError(err, "上传错误", false)
      // 返回值
      utils.Fail(ctx, "文件保存失败", nil)
      return
    }
    // 返回值
    utils.Success(ctx, "上传成功", saveDir)
    return
  }
}

这里需要注意的是:

  1. flag.String() 返回的是一个指针地址,所以使用时需要前缀加*
  2. 创建目录文件夹时权限尽量在0755
  3. 多文件上传逻辑类型,只不过是有个循环的过程,这里就不体现了

说到这里,就全部实现了,上传图片等相关功能!

更多功能请持续关注!!!!!

欢迎各位加我的微信(jobhandsome)跟我一起完成并推动项目的发展

在这里插入图片描述

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK