yinbangzhong
2024-06-17 db7e3c55cef94793dcc0b651c90e5c8b21b8bcc9
controllers/audio.go
@@ -9,6 +9,7 @@
   "mime/multipart"
   "os"
   "path"
   "path/filepath"
   "speechAnalysis/constvar"
   "speechAnalysis/extend/code"
   "speechAnalysis/extend/util"
@@ -28,66 +29,88 @@
// @Tags      音频
// @Summary   上传音频
// @Produce   application/json
// @Param file formData file false "音频文件"
// @Param files formData []file false "多个音频文件"
// @Param files formData []file false "多文件上传"
// @Success   200 {object} util.Response "成功"
// @Router    /api-sa/v1/audio/upload [post]
func (slf AudioCtl) Upload(c *gin.Context) {
   f := func(header *multipart.FileHeader) error {
      logFormat := "%s,%s   "
   var headers []*multipart.FileHeader
   if len(c.Request.MultipartForm.File["file"]) > 1 {
      headers = c.Request.MultipartForm.File["file"]
   } else {
      util.ResponseFormat(c, code.RequestParamError, "文件需要一一对应")
      return
   }
   audio := &models.Audio{}
   for _, header := range headers {
      filename := path.Base(header.Filename)
      arr := strings.Split(filename, "_")
      if len(arr) != 6 {
         //util.ResponseFormat(c, code.RequestParamError, "文件名称错误")
         return errors.New(fmt.Sprintf(logFormat, filename, "文件名称错误"))
         util.ResponseFormat(c, code.RequestParamError, "文件名称错误")
         return
      }
      _, err := models.NewAudioSearch().SetName(filename).First()
      if err != gorm.ErrRecordNotFound {
         //util.ResponseFormat(c, code.RequestParamError, "重复上传")
         return errors.New(fmt.Sprintf(logFormat, filename, "重复上传"))
         util.ResponseFormat(c, code.RequestParamError, "重复上传")
         return
      }
      oss := upload.NewOss()
      filePath, filename, uploadErr := oss.UploadFile(header)
      if uploadErr != nil {
         logx.Errorf("upload audio err: %v", err)
         //util.ResponseFormat(c, code.RequestParamError, "上传失败")
         return errors.New(fmt.Sprintf(logFormat, filename, "上传失败"))
         util.ResponseFormat(c, code.RequestParamError, "上传失败")
         return
      }
      if filepath.Ext(filename) == ".mp3" || filepath.Ext(filename) == ".wav" {
      timeStr := arr[4] + strings.Split(arr[5], ".")[0]
      t, err := time.ParseInLocation("20060102150405", timeStr, time.Local)
      if err != nil {
         //util.ResponseFormat(c, code.RequestParamError, "时间格式不对")
         return errors.New(fmt.Sprintf(logFormat, filename, "上传失败"))
            util.ResponseFormat(c, code.RequestParamError, "时间格式不对")
            return
      }
      audio := &models.Audio{
         Name:             filename,
         Size:             header.Size,
         FilePath:         filePath,
         AudioStatus:      constvar.AudioStatusUploadOk,
         LocomotiveNumber: arr[0],
         TrainNumber:      arr[1],
         DriverNumber:     arr[2],
         Station:          arr[3],
         OccurrenceAt:     t,
         IsFollowed:       0,
         audio.Name = filename
         audio.Size = header.Size
         audio.FilePath = filePath
         audio.AudioStatus = constvar.AudioStatusUploadOk
         audio.LocomotiveNumber = arr[0]
         audio.TrainNumber = arr[1]
         audio.DriverNumber = arr[2]
         audio.Station = arr[3]
         audio.OccurrenceAt = t
         audio.IsFollowed = 0
      }
      if err = models.NewAudioSearch().Create(audio); err != nil {
         //util.ResponseFormat(c, code.SaveFail, "上传失败")
         return errors.New(fmt.Sprintf(logFormat, filename, "上传失败"))
      if filepath.Ext(filename) == ".txt" {
         audio.TxtFilePath = filePath
         //读取filepath文件内容到bts
         bts, err := os.ReadFile(filePath)
         if err != nil {
            util.ResponseFormat(c, code.RequestParamError, "读取文件失败")
            return
         }
         //解析 交路号:123_公里标:321
         fileds := string(bts)
         arr = strings.Split(fileds, "_")
         if len(arr) > 1 {
            util.ResponseFormat(c, code.RequestParamError, "文件内容格式不对")
            return
         } else {
            RouteNumber := strings.Split(arr[0], ":")
            KilometerMarker := strings.Split(arr[1], ":")
            if len(RouteNumber) > 1 && len(KilometerMarker) > 1 {
               audio.RouteNumber = RouteNumber[1]
               audio.KilometerMarker = KilometerMarker[1]
            } else {
               util.ResponseFormat(c, code.RequestParamError, "文件内容格式不对")
               return
            }
         }
      }
   }
   if err := models.NewAudioSearch().Create(audio); err != nil {
      util.ResponseFormat(c, code.SaveFail, "上传失败")
      return
      }
      go func() {
         var trainInfoNames = []string{arr[0], arr[1], arr[3]}
      var trainInfoNames = []string{audio.LocomotiveNumber, audio.TrainNumber, audio.Station}
         var (
            info   *models.TrainInfo
            err    error
@@ -107,35 +130,7 @@
            }
            parent = *info
         }
      }()
      return nil
   }
   var headers []*multipart.FileHeader
   _, header, _ := c.Request.FormFile("file")
   if header != nil {
      headers = append(headers, header)
   }
   if len(c.Request.MultipartForm.File["files"]) > 0 {
      headers = c.Request.MultipartForm.File["files"]
   }
   var errs []error
   for _, h := range headers {
      if e := f(h); e != nil {
         errs = append(errs, e)
      }
   }
   if len(errs) > 0 {
      var r strings.Builder
      for _, e := range errs {
         r.WriteString(e.Error())
      }
      util.ResponseFormat(c, code.RequestParamError, r.String())
      return
   } else {
      util.ResponseFormat(c, code.Success, "添加成功")
      return
   }
}
func (slf AudioCtl) ParamsCheck(filename string) (err error) {
@@ -289,13 +284,22 @@
      util.ResponseFormat(c, code.InternalError, "查询失败")
      return
   }
   if audio.FilePath == "" {
   filepath := ""
   if params.Filetype == 1 {
      filepath = audio.FilePath
      c.Header("Content-Type", "audio/mpeg") // 设置音频文件类型
   }
   if params.Filetype == 2 {
      filepath = audio.TxtFilePath
      //设置Content-Type为txt文件类型
      c.Header("Content-Type", "text/plain")
   }
   if filepath == "" {
      util.ResponseFormat(c, code.InternalError, "查询失败")
      return
   }
   file, err := os.Open(audio.FilePath)
   file, err := os.Open(filepath)
   if err != nil {
      util.ResponseFormat(c, code.InternalError, "文件打开失败")
      return
@@ -310,7 +314,6 @@
   c.Header("Content-Disposition", "inline; filename="+audio.Name) // 在浏览器中直接打开
   c.Header("Content-Length", fmt.Sprint(fileInfo.Size()))
   c.Header("Content-Type", "audio/mpeg") // 设置音频文件类型
   if _, err := io.Copy(c.Writer, file); err != nil {
      util.ResponseFormat(c, code.InternalError, "文件传输失败")