先建立一個 index.html 檔,把下面 HTML 語法複製貼上,再將 html 檔移動到 Golang 專案下

<html>
<head>
<title>Golang upload</title>
</head>
<body>
<form id="uploadForm" method="POST" enctype="multipart/form-data" action="http://127.0.0.1:8080/upload">
<p>Golang upload</p>
<input type="FILE" id="file" name="file" />
<input type="SUBMIT" value="upload">
</form>
</body>
</html>





Golang 程式碼:

package main

import (
"html/template"
"io/ioutil"
"net/http"
"os"
)

func indexHandle(w http.ResponseWriter, r *http.Request) {
uploadTemplate := template.Must(template.ParseFiles("index.html"))
uploadTemplate.Execute(w, nil)
}

func uploadHandle(w http.ResponseWriter, r *http.Request) {
file, head, _ := r.FormFile("file")
defer file.Close()
bytes, _ := ioutil.ReadAll(file)
w.Write(bytes)
ioutil.WriteFile(head.Filename, bytes, os.ModeAppend)
}

func main() {
http.HandleFunc("/", indexHandle)
http.HandleFunc("/upload", uploadHandle)
http.ListenAndServe(":8080", nil)
}







    全站熱搜

    黃彥霖 發表在 痞客邦 留言(0) 人氣()