I have a very simple web server in Go, and on one page there is a form to upload a file:
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*"><br>
Description: <input type="text" name="descr"><br>
<input type="submit">
</form>
And I read the file in Go like this:
func imageUpload(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
_,imageHead,err := r.FormFile("image")
if err != nil {
log.Printf("Error with upload: %s", err)
return
}
imageDesc := r.FormValue("descr")
fileSize := .... ???
log.Printf("Recibí %s <%s> (%d bytes)", imageHead.Filename, imageDesc, fileSize)
}
But what do I do to get fileSize
?
imageData
is a multipart.File , which exposes io.Reader, io.ReaderAt, io.Seeker and io.Closer . But don't file directly? So the only option is to read the io.Reader to see how many bytes I have? Or is there another more efficient option?
The only reliable way to get the exact size of the file would be to read the whole thing to count the bytes. One possible way would be using io.ReadFull .
Otherwise, that information could be sent by the client explicitly in some header of the request, but here you would depend on the client's commitment to always send this information.
Additionally, it might be wise to use something like io.LimitReader to read up to a certain limit.
1- If you are not going to copy the file to the server you could get the size of the file using js and assign the value to a hidden input and read it along with the file upload.
2- If you are going to copy the file to the server then you must create a file (os.File), from which you can read its size after having copied the content, in your code you are not doing anything with the content of the file, if you are going to copy it to the server you need to read the content: