Access to downloaded files in the Golang

I have problems accessing the files that I upload using golang. I am really new to this language and have experienced more than a few attempts - I also cannot find the answers to this question.

What am I doing wrong? In this code, I never end up in a block where it lists the number of downloaded files.

func handler(w http.ResponseWriter, r *http.Request) { fmt.Println("handling req...") if r.Method =="GET"{ fmt.Println("GET req...") } else { //parse the multipart stuff if there err := r.ParseMultipartForm(15485760) // if err == nil{ form:=r.MultipartForm if form==nil { fmt.Println("no files...") } else { defer form.RemoveAll() // i never see this actually occur fmt.Printf("%d files",len(form.File)) } } else { http.Error(w,err.Error(),http.StatusInternalServerError) fmt.Println(err.Error()) } } //fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) fmt.Println("leaving...") } 

Update

I managed to get this code to work. It's great. The answer below shows how to make this asynchronous, which may be a better code example than mine.

+6
source share
2 answers

Answer Download the latest version of golang.

I ran into a problem before using old versions of golang, I don't know what happened, but with the last golang its work. =)

My download handler code is below ... Full code: http://noypi-linux.blogspot.com/2014/07/golang-web-server-basic-operatons-using.html

  // parse request const _24K = (1 << 10) * 24 if err = req.ParseMultipartForm(_24K); nil != err { status = http.StatusInternalServerError return } for _, fheaders := range req.MultipartForm.File { for _, hdr := range fheaders { // open uploaded var infile multipart.File if infile, err = hdr.Open(); nil != err { status = http.StatusInternalServerError return } // open destination var outfile *os.File if outfile, err = os.Create("./uploaded/" + hdr.Filename); nil != err { status = http.StatusInternalServerError return } // 32K buffer copy var written int64 if written, err = io.Copy(outfile, infile); nil != err { status = http.StatusInternalServerError return } res.Write([]byte("uploaded file:" + hdr.Filename + ";length:" + strconv.Itoa(int(written)))) } } 
+6
source

If you know that the key is to download the file, you can make it a little easier, I think (this is not verified):

 infile, header, err := r.FormFile("file") if err != nil { http.Error(w, "Error parsing uploaded file: "+err.Error(), http.StatusBadRequest) return } // THIS IS VERY INSECURE! DO NOT DO THIS! outfile, err := os.Create("./uploaded/" + header.Filename) if err != nil { http.Error(w, "Error saving file: "+err.Error(), http.StatusBadRequest) return } _, err = io.Copy(outfile, infile) if err != nil { http.Error(w, "Error saving file: "+err.Error(), http.StatusBadRequest) return } fmt.Fprintln(w, "Ok") 
+4
source

Source: https://habr.com/ru/post/953248/


All Articles