Vditor上传图片Gin框架接口接收多图上传

更新于 2022-10-15 16:09 127
专栏: 前端文章 标签: vue

最近开发日历记事本V2版本(Gin+vue3)用到了,记录一下

Vditor图片上传官方文档:文档

  1. func (a *FileApi) UploadFiles(c *gin.Context) {
  2. userInfo, _ := base.GetCurrentUserInfo(c)
  3. configUpload := global.Config.GetValueString("base", "source_path")
  4. form, err := c.MultipartForm()
  5. if err != nil {
  6. apiReturn.Error(c, "上传失败")
  7. return
  8. }
  9. files := form.File["files[]"]
  10. errFiles := []string{}
  11. succMap := map[string]string{}
  12. for _, f := range files {
  13. fileExt := strings.ToLower(path.Ext(f.Filename))
  14. fileName := cmn.Md5(fmt.Sprintf("%s%s", f.Filename, time.Now().String()))
  15. fildDir := fmt.Sprintf("%s/%d/%d/%d/", configUpload, time.Now().Year(), time.Now().Month(), time.Now().Day())
  16. isExist, _ := cmn.PathExists(fildDir)
  17. if !isExist {
  18. os.MkdirAll(fildDir, os.ModePerm)
  19. }
  20. filepath := fmt.Sprintf("%s%s%s", fildDir, fileName, fileExt)
  21. if c.SaveUploadedFile(f, filepath) != nil {
  22. errFiles = append(errFiles, f.Filename)
  23. } else {
  24. // 成功
  25. // 像数据库添加记录
  26. mFile := models.File{}
  27. mFile.AddFile(userInfo.ID, f.Filename, filepath)
  28. succMap[f.Filename] = filepath[1:]
  29. }
  30. }
  31. apiReturn.SuccessData(c, gin.H{
  32. "succMap": succMap,
  33. "errFiles": errFiles,
  34. })
  35. }