上传部分
网页的代码
这里必须填 enctype="multipart/form-data"
<!DOCTYPE html>
<html>
<head>
<title>uplaod</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
文件:<input type="file" name="file"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
go代码
package main
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) { //解析上传页面的模板
t, _ := template.ParseFiles("view/index.html")
t.Execute(w, nil)
}
func upload(w http.ResponseWriter, r *http.Request) { //上传函数
file, fileHeader, _ := r.FormFile("file")
b, _ := ioutil.ReadAll(file)
ioutil.WriteFile("D:/"+fileHeader.Filename, b, 0777)
fmt.Fprintln(w, "上传成功")
}
func main() {
server := http.Server{Addr: "localhost:8080"}
http.HandleFunc("/", index)
http.HandleFunc("/upload", upload)
server.ListenAndServe()
}
下载部分
网页的代码
<!DOCTYPE html>
<html>
<head>
<title>download</title>
</head>
<body>
<a href="download?filename=abc.txt">下载</a>
</body>
</html>
go代码
package main
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) { //解析下载页面的模板
t, _ := template.ParseFiles("view/index.html")
t.Execute(w, nil)
}
func download(w http.ResponseWriter, r *http.Request) { //下载函数
filename := r.FormValue("filename")
f, err := ioutil.ReadFile("D:/" + filename) //在哪个目录里下载
if err != nil {
fmt.Fprintln(w, "文件下载失败,", err)
return
}
h := w.Header()
h.Set("Content-Type", "application/octet-stream")
//下载时显示的名称,要不然都是download这个名字
h.Set("Content-Disposition", "attachment;filename="+filename)
w.Write(f)
}
func main() {
server := http.Server{Addr: "localhost:8080"}
http.HandleFunc("/", index)
http.HandleFunc("/download", download)
server.ListenAndServe()
}