Rabarar's Blog

A blogging framework for mild hackers.

Golang File Upload Processing

| Comments

Here’s a quick sample (credit: astaxie) that demonstrates how to upload a file in golang:

There are two things going on here: First is the handler section that processes the GET and then the section handling the POST (to be more accurate, we should check the r.Method once more to see if it’s exactly the POST method).

In the get, we generate a token to ensure that the file we receive is indeed the one requested from the GET. Although in this code, there isn’t a check to see that that’s indeed the case in the POST (left as an exercise for the reader).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
   http.HandleFunc("/upload", upload)

  // upload logic
  func upload(w http.ResponseWriter, r *http.Request) {
      fmt.Println("method:", r.Method)
      if r.Method == "GET" {
          crutime := time.Now().Unix()
          h := md5.New()
          io.WriteString(h, strconv.FormatInt(crutime, 10))
          token := fmt.Sprintf("%x", h.Sum(nil))

          t, _ := template.ParseFiles("upload.gtpl")
          t.Execute(w, token)
      } else {
          r.ParseMultipartForm(32 << 20)
          file, handler, err := r.FormFile("uploadfile")
          if err != nil {
              fmt.Println(err)
              return
          }
          defer file.Close()
          fmt.Fprintf(w, "%v", handler.Header)
      fmt.Printf("value=%s\n", r.FormValue("token"))
          f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
          if err != nil {
              fmt.Println(err)
              return
          }
          defer f.Close()
          io.Copy(f, file)
      }
  }

And the template above, upload.gtpl looks like:

1
2
3
4
5
6
7
8
9
10
11
12
 <html>
  <head>
      <title>Upload file</title>
  </head>
  <body>
  <form enctype="multipart/form-data" action="http://127.0.0.1:9090/upload" method="post">
          <input type="file" name="uploadfile" />
          <input type="hidden" name="token" value=""/>
          <input type="submit" value="upload" />
  </form>
  </body>
  </html>

Comments