在Golang中访问上传的文件

时间:2013-09-05 15:08:26

标签: http file-upload go

我在访问上传w / golang的文件时遇到问题。我对这门语言很陌生并经历过多次尝试 - 无法在网上找到任何答案。

我做错了什么?在这段代码中,我从未到过列出上传文件数量的块。

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...")
}

更新

我能够让上面的代码工作。哪个好。下面的答案显示了如何进行异步,这可能是比我更好的代码示例。

2 个答案:

答案 0 :(得分:10)

回答 下载最新的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))))  
       }  
  }  

答案 1 :(得分:4)

如果你知道文件上传的密钥,你可以让它更简单一些(我没想过):

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")