2022-03-08 12:01:51 +01:00
|
|
|
package utils
|
2022-03-08 20:37:49 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ReceiveFile Permet de récupérer un fichier sur un reader
|
2022-03-13 12:29:05 +01:00
|
|
|
func ReceiveFile(path string, fileSize int, reader *bufio.Reader) bool {
|
|
|
|
file, fileErr := os.Create(path)
|
2022-03-08 20:37:49 +01:00
|
|
|
if fileErr != nil {
|
|
|
|
return false
|
|
|
|
}
|
2022-03-13 17:04:24 +01:00
|
|
|
|
2022-03-08 20:37:49 +01:00
|
|
|
defer file.Close()
|
2022-03-12 19:12:19 +01:00
|
|
|
|
|
|
|
// Params
|
2022-03-10 14:35:41 +01:00
|
|
|
buffer := make([]byte, 1024)
|
2022-03-12 19:12:19 +01:00
|
|
|
currentSize := 0
|
2022-03-10 14:35:41 +01:00
|
|
|
|
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) {
|
2022-03-12 19:12:19 +01:00
|
|
|
// Retrieving file
|
2022-03-10 14:35:41 +01:00
|
|
|
for currentSize < fileSize {
|
|
|
|
length, err := reader.Read(buffer)
|
|
|
|
if err != nil {
|
2022-03-13 17:04:24 +01:00
|
|
|
return false, true
|
2022-03-10 14:35:41 +01:00
|
|
|
}
|
2022-03-12 19:12:19 +01:00
|
|
|
_, err = file.WriteAt(buffer, int64(currentSize))
|
|
|
|
if err != nil {
|
2022-03-13 17:04:24 +01:00
|
|
|
return false, true
|
2022-03-12 19:12:19 +01:00
|
|
|
}
|
2022-03-10 14:35:41 +01:00
|
|
|
currentSize += length
|
2022-03-12 19:12:19 +01:00
|
|
|
check := fileSize - currentSize
|
|
|
|
if 1024 > check && check > 0 {
|
|
|
|
buffer = make([]byte, check)
|
|
|
|
}
|
2022-03-08 20:37:49 +01:00
|
|
|
}
|
2022-03-13 17:04:24 +01:00
|
|
|
return false, false
|
|
|
|
}
|