欢迎光临
我们一直在努力

go语言学习例子No.11–获取文件夹下面的文件列表和简单下载功能

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()
}

就是下面这个样子,很简单

 收藏 (0) 打赏

您可以选择一种方式赞助本站

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:家里蹲的狐狸 » go语言学习例子No.11–获取文件夹下面的文件列表和简单下载功能

分享到: 生成海报
avatar

热门文章

  • 评论 抢沙发

    • QQ号
    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址

    登录

    忘记密码 ?

    切换登录

    注册

    我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活