您的位置:首页 > 理论基础 > 计算机网络

Golang实现http文件上传小功能

2016-04-15 22:29 549 查看
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>`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息