欢迎光临
我们一直在努力

go语言学习例子No.10–文件的上传和下载

上传部分

网页的代码

这里必须填 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()
}
 收藏 (0) 打赏

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

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:家里蹲的狐狸 » go语言学习例子No.10–文件的上传和下载

分享到: 生成海报
avatar

热门文章

  • 评论 抢沙发

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

    登录

    忘记密码 ?

    切换登录

    注册

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