Go 语言上传文件
2、执行go build;
3、打开浏览器运行:http://127.0.0.1:8080;
4、选择文件提交就可以看到效果;
Html代码:
<html>
<head>
<title>Golang upload</title>
</head>
<body>
<form id="uploadForm" method="POST" enctype="multipart/form-data" action="/upload">
<p>Golang upload</p>
<input type="FILE" id="file" name="file" />
<input type="SUBMIT" value="upload">
</form>
</body>
</html>
Go 代码:
package main
import (
"html/template"
"io/ioutil"
"log"
"net/http"
)
var uploadTemplate = template.Must(template.ParseFiles("index.html"))
func indexHandle(w http.ResponseWriter, r *http.Request) {
if err := uploadTemplate.Execute(w, nil); err != nil {
log.Fatal("Execute: ", err.Error())
return
}
}
func uploadHandle(w http.ResponseWriter, r *http.Request) {
file, _, err := r.FormFile("file")
if err != nil {
log.Fatal("FormFile: ", err.Error())
return
}
defer func() {
if err := file.Close(); err != nil {
log.Fatal("Close: ", err.Error())
return
}
}()
bytes, err := ioutil.ReadAll(file)
if err != nil {
log.Fatal("ReadAll: ", err.Error())
return
}
w.Write(bytes)
}
func main() {
http.HandleFunc("/", indexHandle)
http.HandleFunc("/upload", uploadHandle)
http.ListenAndServe(":8080", nil)
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。