前端之家收集整理的这篇文章主要介绍了
Golang实现http文件上传小功能,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
http.HandleFunc("/",index)
http.HandleFunc("/upload",upload)
http.ListenAndServe(":1789",nil)
}
func upload(w http.ResponseWriter,r *http.Request) {
r.ParseMultipartForm(32 << 20)
file,handler,err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
f,err := os.OpenFile(handler.Filename,os.O_WRONLY|os.O_CREATE,0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f,file)
fmt.Fprintln(w,"upload ok!")
}
func index(w http.ResponseWriter,r *http.Request) {
w.Write([]byte(tpl))
}
const tpl = `<html>
<head>
<title>上传文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input type="file" name="uploadfile" />
<input type="hidden" name="token" value="{...{.}...}"/>
<input type="submit" value="upload" />
</form>
</body>
</html>`
原文链接:https://www.f2er.com/go/189843.html