Go upload file
How to handle file uploads in Go using r.FormFile, reading the uploaded content, and displaying it in an HTML form.
This example demonstrates handling file uploads in Go. When the server receives a POST request, it extracts the uploaded file using r.FormFile, reads its content with ioutil.ReadAll, and displays it on the page. The HTML form uses enctype="multipart/form-data" which is required for file uploads.
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
)
func main() {
http.HandleFunc("/", foo)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
func foo(w http.ResponseWriter, r *http.Request) {
var s string
fmt.Printf("Request method: %v\n", r.Method)
if r.Method == http.MethodPost {
f, h, err := r.FormFile("q")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
fmt.Printf("File: %v\n", f)
fmt.Printf("Headers: %v\n", h)
fmt.Printf("Error: %v\n", err)
bs, err := ioutil.ReadAll(f)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s = string(bs)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
io.WriteString(w, `
<form method="POST" enctype="multipart/form-data">
<input type="file" name="q">
<input type="submit">
</form>
` + s)
}
This post is licensed under CC BY 4.0 by the author.