1. 程式人生 > 程式設計 >Golang實現非同步上傳檔案支援進度條查詢的方法

Golang實現非同步上傳檔案支援進度條查詢的方法

業務背景

業務需求要求開發一個非同步上傳檔案的介面,並支援上傳進度的查詢。

需求分析

ZIP壓縮包中,包含一個csv檔案和一個圖片資料夾,要求:解析csv資料存入mongo,將圖片資料夾中的圖片資訊對應上csv中的人員資訊。

ZIP壓縮包解壓

使用golang自帶的"archive/zip" 包解壓。

func decompressZip(filePath,dest string) (string,string,error) {
  var csvName string
  imageFolder := path.Base(filePath)
  ext := path.Ext(filePath)
  folderName := strings.TrimSuffix(imageFolder,ext)
  src,err := os.Open(filePath)
  if err != nil {
    return "","",err
  }
  defer src.Close()

  zipFile,err := zip.OpenReader(src.Name())
  if err != nil {
    return "",err
  }
  defer zipFile.Close()

  err = os.MkdirAll(path.Join(dest,folderName),os.ModePerm)
  for _,innerFile := range zipFile.File {
    info := innerFile.FileInfo()
    if info.IsDir() {
      continue
    }
    dst,err := os.Create(path.Join(dest,folderName,info.Name()))
    if err != nil {
      fmt.Println(err.Error())
      continue
    }
    src,err := innerFile.Open()
    if err != nil {
      fmt.Println(err.Error())
      continue
    }
    io.Copy(dst,src)
  }
  destPath,err := ioutil.ReadDir(path.Join(dest,folderName))
  if err != nil {
    return "",err
  }
  for _,v := range destPath {
    if path.Ext(v.Name()) == ".csv" {
      csvName = path.Join(dest,v.Name())
    }
  }
  return folderName,csvName,nil
}

在這個解壓的過程中,壓縮包的樹結構只能到2層

import.zip

┝┅┅import.csv

┖┅┅images

在解壓後,所有的檔案都會在同一個目錄下,既images中的圖片會變成和.csv檔案同級

驗證csv檔案編碼格式是否為UTF-8

func ValidUTF8(buf []byte) bool {
  nBytes := 0
  for i := 0; i < len(buf); i++ {
    if nBytes == 0 {
      if (buf[i] & 0x80) != 0 { //與操作之後不為0,說明首位為1
        for (buf[i] & 0x80) != 0 {
          buf[i] <<= 1 //左移一位
          nBytes++   //記錄字元共佔幾個位元組
        }
        if nBytes < 2 || nBytes > 6 { //因為UTF8編碼單字元最多不超過6個位元組
          return false
        }
        nBytes-- //減掉首位元組的一個計數
      }
    } else { //處理多位元組字元
      if buf[i]&0xc0 != 0x80 { //判斷多位元組後面的位元組是否是10開頭
        return false
      }
      nBytes--
    }
  }
  return nBytes == 0
}

後續支援utf-8轉碼

這個utf8編碼判斷方法是網上down下來的,後續優化一下

主邏輯

type LineWrong struct {
  LineNumber int64 `json:"line_number"`
  Msg    string `json:"msg"`
}

func Import(/*自定義引數*/){
  // decompress zip file to destination address
  folder,err := Decompress(path.Join(constant.FolderPrefix,req.FilePath),dest)
  if err != nil {
    fmt.Println(err.Error())
  }

  // check if the file encoding is utf8
  b,err := ioutil.ReadFile(csvName)
  if err != nil {
    fmt.Println(err.Error())
  }
  if !utils.ValidUTF8(b) {
    fmt.Println(errors.New("資料編碼錯誤,請使用utf-8格式csv!"))
  }

  // create goroutine to analysis data into mongodb
  var wg sync.WaitGroup
  wg.Add(1)

  // used to interrupt goroutine
  resultChan := make(chan error)
  // used to record wrong row in csv
  lW := make(chan []LineWrong)
  go func(ctx *gin.Context,Name,csvPath,dir,folder string) {
    defer wg.Done()
    tidT,ciT,lwT,err := importCsv(ctx,folder)
    resultChan <- err
    if err != nil {
      fmt.Println(err.Error())
    }
    lW <- lwT
    if len(lwT) == 0 {
      importClassData(ctx,tidT,ciT)
    }
  }(ctx,req.Name,dest,folder)

  err = <-resultChan
  lineWrong := <-lW
  close(lW)
  ···
}

// pre-analysis data in csv and through wrong data with line numbers and information
func importCsv()(){
  ···
}

// analysis data again and save data into mongodb,if is there any error,through them same as import()
func importClassData()(){
  ···
  conn,err := connect()
  if err != nil {
    return err
  }
  defer conn.Close()
  conn.Do("hset",taskId,"task_id",(curLine*100)/totalLines)
  ···
}

將錯誤資訊以channel接收,使用package "sync" 的sync.WaitGroup 控制非同步協程。在入庫的過程中,將當前的進度存入redis。

查詢進度介面

func QueryImport()(){
  conn,err := connect()
  if err != nil {
    return nil,err
  }
  defer conn.Close()

  progress,_ := conn.Do("hget",key,field)
  if pro,ok := progress.([]uint8); ok {
    ba := []byte{}
    for _,b := range pro {
      ba = append(ba,byte(b))
    }
    progress,_ = strconv.Atoi(string(ba))
  }
  return progress
}

從redis中取出來的資料是[]uint8型別資料,先斷言,然後轉型別返回。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。