Answer the question
In order to leave comments, you need to log in
How not to copy the file twice when getting the hash?
The file is uploaded to the server and stored in multipart.File, then you must first get its hash, and only then create the file on disk. The problem is that the io.Copy function is called twice. First, in the hash getting function, and then when copying from the form to a file on disk. How can this be avoided?
i.e. the first time it is called here
hash, err := GetFileHashMD5(fileFromForm)
// это уже в другом пакете
func GetFileHashMD5(file io.Reader) (hashed string, err error) {
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
hashed = hex.EncodeToString(hash.Sum(nil))
return
}
_, err = io.Copy(createdFile, fileFromForm)
Answer the question
In order to leave comments, you need to log in
If the file is small and can be read into memory then the algorithm might be:
// вычитываете содержимое при помощи io.Reader'a, например
fh, handler, err := r.FormFile("myFile")
fileBytes, err := io.ReadAll(fh)
// считаете md5
md5sum := md5.Sum(fileBytes)
// сохраняете файл
f, err := os.Create("/file_path/file_name")
defer f.Close()
f.Write(fileBytes)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question