I upload the file to the server, I want to know the size and then copy it. after the image.DecodeConfig function, the contents of the file variable change and io.Copy does not copy. Below is an example with details:

func handlerRequest(w http.ResponseWriter, r *http.Request) { file, handler, err := r.FormFile("file") if err != nil { error_handler() } defer file.Close() path := "images/"+handler.Filename f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { error_handler() } defer f.Close() fmt.Printf("%s\n", file) // {%!s(*io.SectionReader=&{0xc4200f8420 0 0 2954043})} im, _, err := image.DecodeConfig(file) fmt.Printf("%s\n", file) // {%!s(*io.SectionReader=&{0xc4200f8420 0 28672 2954043})} fmt.Printf("%s\n", im) // {%!s(*color.modelFunc=&{0x608520}) %!s(int=3072) %!s(int=2048)} io.Copy(f, file) } 

in this case, no copying takes place (I noticed that instead of 0 after the call to DecodeConfig, it turned out 28672). but if I transfer image.DecodeConfig after io.Copy and open the file os.Open, I get the sizes and copy it like this:

 // ... код который выше кроме image.DecodeConfig и fmt.Printf io.Copy(f, file) f1, err := os.Open(path) if err != nil { error_handler() } defer f1.Close() im, _, err := image.DecodeConfig(f1) 

Is it possible to know the size of the image before copying? that would not have to additionally open the file: (

    1 answer 1

    Buffer reads like this:

     buf := &bytes.Buffer{} tr := io.TeeReader(file, buf) im, _, err := image.DecodeConfig(tr) if err != nil { panic(err) } mr := io.MultiReader(buf, file) _, err = io.Copy(f, mr) if err != nil { panic(err) } 
    • Thanks Ainar-G, just what you need :) - Jenyokcoder