How to validate size files before save them in the server/db?

I am trying to save files(images) from a user input but I need to validate the type and the size file, I already know how to validate the type file but I couldn’t figure out how to validate the files’ size, any help is welcome!

if you have image as []byte then size = len([]byte)

Now I am using:

req.ParseMultipartForm(1000000) // to parse the request
formData := req.MultipartForm // it gives me a *Form
formData.File["images"] // and this map[string][]*FileHeader

So I think I have no []byte

Hey @Gustavo_Diaz,

One way I’ve seen that may help you do this is to use the file’s seek method, here’s an example once you have the file header:

// Open the FileHeader's associated file.
file, err := fh.Open()
if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
	return
}
defer file.Close()

// Seek to the end of the file.
size, err := file.Seek(0, io.SeekEnd)
if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
	return
}

// Print the size of the file.
fmt.Println(size)

// Set seek back to the start.
_, err = file.Seek(0, 0)
if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
	return
}
3 Likes

Oh man thanks a lot! it worked I have tried different approaches but anything had worked, thanks.

Glad to help :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.