StoreBackEnd/pkg/utils/FileReceiver.go

48 lines
945 B
Go
Raw Normal View History

package utils
import (
"bufio"
"os"
)
// ReceiveFile Permet de récupérer un fichier sur un reader
func ReceiveFile(path string, fileSize int, reader *bufio.Reader) bool {
file, fileErr := os.Create(path)
if fileErr != nil {
return false
}
2022-03-13 17:04:24 +01:00
defer file.Close()
// Params
buffer := make([]byte, 1024)
currentSize := 0
2022-03-15 17:11:31 +01:00
// Copy file
2022-03-13 17:04:24 +01:00
b, done := copyFile(currentSize, fileSize, reader, buffer, file)
if done {
return b
}
return true
}
func copyFile(currentSize int, fileSize int, reader *bufio.Reader, buffer []byte, file *os.File) (bool, bool) {
// Retrieving file
for currentSize < fileSize {
length, err := reader.Read(buffer)
if err != nil {
2022-03-13 17:04:24 +01:00
return false, true
}
_, err = file.WriteAt(buffer, int64(currentSize))
if err != nil {
2022-03-13 17:04:24 +01:00
return false, true
}
currentSize += length
check := fileSize - currentSize
if 1024 > check && check > 0 {
buffer = make([]byte, check)
}
}
2022-03-13 17:04:24 +01:00
return false, false
}