I\'m having issues with accessing files i upload w/ golang. I\'m really new to the language and have gone through more than a few attempts-- can\'t find any answers to this onli
Answer Download the latest golang release.
I experienced the problem before, using the old golang versions, I do not know what happened, but with the latest golang its working. =)
My upload handler code below... Full code at: 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))))
}
}
If you know they key of the file upload you can make it a bit simpler I think (this is not tested):
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")