package main
import (
"fmt"
"io/ioutil"
)
func main() {
files, _ := ioutil.ReadDir("./")
for _, f := range files {
fmt.Println(f.Name())
}
}
在网页上显示
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件夹列表</title>
</head>
<body>
<table border="1">
<tr>
<th>文件名</th>
<th>文件大小</th>
</tr>
{{range .}}
<tr>
<td>{{.Name}}</td>
<td>{{.Size}}</td>
<td><a href="download?filename={{.Name}}">下载</a></td>
</tr>
{{end}}
</table>
</body>
</html>
package main
import (
"html/template"
"io/ioutil"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) { //解析上传页面的模板
files, _ := ioutil.ReadDir("./")
t, _ := template.ParseFiles("view/index.html")
t.Execute(w, files)
}
func main() {
server := http.Server{Addr: "localhost:8080"}
http.HandleFunc("/", index)
server.ListenAndServe()
}
添加下载功能
package main
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) { //解析上传页面的模板
files, _ := ioutil.ReadDir("./")
t, _ := template.ParseFiles("view/index.html")
t.Execute(w, files)
}
func download(w http.ResponseWriter, r *http.Request) { //下载函数
filename := r.FormValue("filename")
f, err := ioutil.ReadFile("./" + 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()
}
就是下面这个样子,很简单