我在访问使用 golang 上传的文件时遇到问题。我对这门语言真的很陌生,并且已经进行了多次尝试——也无法在网上找到任何答案。
我做错了什么?在这段代码中,我从来没有到达列出上传文件数量的 block 。
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...")
}
更新
我能够让上面的代码工作。这很棒。下面的答案显示了如何进行异步操作,这可能是比我的更好的代码示例。
最佳答案
回答 下载最新的 golang 版本。
我之前遇到过这个问题,使用旧的 golang 版本,我不知道发生了什么,但是使用最新的 golang 可以正常工作。 =)
我的上传处理程序代码如下... 完整代码: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))))
}
}
关于http - 在 Golang 中访问上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18639929/