code example from the book "Go in practice":

mr, err := r.MultipartReader() if err != nil { panic("Failed to read multipart message: ") } length := r.ContentLength for { part, err := mr.NextPart() if err == io.EOF { break } var read int64 var p float32 filename := part.FileName() dst, err := os.Create("/tmp/dstfile." + filename) if err != nil { return } for { buffer := make([]byte, 100000) cBytes, err := part.Read(buffer) if err == io.EOF { break } read = read + int64(cBytes) //fmt.Printf("read: %v \n",read ) p = float32(read) / float32(length) * 100 fmt.Printf("progress: %v \n", p) dst.Write(buffer[0:cBytes]) } } 

full code

I'm trying to upload files in this way. As a result, 2 dstfile created, one of which is just a dstfile , the other dstfile.name.extension (approx. dstfile.test.txt ). I tried to load 2 types of files - .txt - which turns out to be empty, and .xls - which in general does not open.

In general, more interested in why .xls does not open.

I use windows 10, go1.8 windows / amd64

PS: there is no specific code in this book.

    1 answer 1

    Refactored option.

    The extra file was created because there was no check for the emptiness of the file name.

    And the files were not recorded correctly, I think so, because part.Read having reached the end of the file, part.Read out an error, but what he thought was not written. So it turned out that the files were curves.

    If not right, correct.

     mr, err := r.MultipartReader() if err != nil { log.Println(err) return } length := r.ContentLength for { part, err := mr.NextPart() if err == io.EOF { break } else if err != nil { log.Println(err) continue } formName := part.FormName() if formName == "" { continue } fileName := part.FileName() if fileName == "" { continue } var read int64 var p float32 dst, err := os.Create("tmp/dstfile." + fileName) if err != nil { log.Println(err) return } buffer := make([]byte, 100000) for { n, err := part.Read(buffer) if err != nil && err != io.EOF { log.Println(err) break } if n == 0 { break } read = read + int64(n) //log.Printf("read: %v \n",read ) p = float32(read) / float32(length) * 100 _, err = dst.Write(buffer[:n]) if err != nil { log.Println(err) break } log.Printf("progress: %v \n", p) } dst.Close() }