Use go to build a simple image upload site

before playing go web server, now use go to build a simple image upload site, the working directory is: ~/photoweb, and ~/photoweb/uploads is used Save the image, the code photoweb.go is in the ~/photoweb directory.

看 server code, ~/photoweb/photoweb.go content:

package main
 
Import (
"io"
"os"
"log"
"net/http"
)

Const (
UPLOAD_DIR = "./uploads"
)

Func uploadHandler(w http.ResponseWriter, r *http.Request) {
If r.Method == "GET" {
    Str := `
<html>
<head>
<meta charset="utf-8">
<title>Upload</title>
</head>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
Choose an image to upload: <input name="image" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>`
    
    io.WriteString(w, str)
}

/ / Process image upload
If r.Method == "POST" {
f, h, err := r.FormFile("image")
If err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
Return
}
Filename := h.Filename
Defer f.Close()

t, err := os.Create(UPLOAD_DIR + "/" + filename)
If err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
Return
}
Defer t.Close()

If _, err := io.Copy(t, f); err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
Return
}
}

}

Func main() {
http.HandleFunc("/upload", uploadHandler)
Err := http.ListenAndServe(":8080", nil)
If err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}

The background code enters the GET branch, returns a html code to the browser, displays it as an html element, allows the user to upload the image, selects the image, clicks the Upload button to upload, the background code enters the POST branch, and the image is saved. ~/photoweb/uploads. Actually check it out, this picture really has this picture.

In order to view the uploaded pictures directly on the browser, you can modify the server code and add Redirect, as follows:

package main
 
Import (
"io"
"os"
"log"
"net/http"
)

Const (
UPLOAD_DIR = "./uploads"
)

Func uploadHandler(w http.ResponseWriter, r *http.Request) {
If r.Method == "GET" {
    Str := `
<html>
<head>
<meta charset="utf-8">
<title>Upload</title>
</head>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
Choose an image to upload: <input name="image" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>`
    
    io.WriteString(w, str)
}

/ / Process image upload
If r.Method == "POST" {
f, h, err := r.FormFile("image")
If err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
Return
}
Filename := h.Filename
Defer f.Close()

t, err := os.Create(UPLOAD_DIR + "/" + filename)
If err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
Return
}
Defer t.Close()

If _, err := io.Copy(t, f); err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
Return
}

http.Redirect(w, r, "/view?id="+filename, http.StatusFound)
}

}

Func isExists(path string) bool {
_, err := os.Stat(path)
If err == nil {
Return true
}
Return os.IsExist(err)
}

Func viewHandler(w http.ResponseWriter, r *http.Request) {
imageId := r.FormValue("id")
imagePath := UPLOAD_DIR + "/" + imageId
If exists := isExists(imagePath); !exists {
http.NotFound(w, r)
Return
}
w.Header().Set("Content-Type", "image")
http.ServeFile(w, r, imagePath)
}

Func main() {
http.HandleFunc("/view", viewHandler)
http.HandleFunc("/upload", uploadHandler)
Err := http.ListenAndServe(":8080", nil)
If err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}

Restart the service, revisit http://127.0.0.1:8080/upload, then select the image, click Upload to upload, the result is in the corresponding directory of the server, and the image is displayed in the browser. .

The above code is very simple, I have written a similar image upload server under Apatch, the reason is basically the same.

好了, not much to say.