goweb中文件上传和文件下载
文件上传
- 文件上传:客户端把上传文件转换为二进制流后发送给服务器,服务器对二进制流进行解析
- HTML表单(form)enctype(Encode Type)属性控制表单在提交数据到服务器时数据的编码类型
- enctype=“application/x-www-form-urlencoded” 默认值,表单数据会被编码为名称/值形式。
- oenctype="multipart/form-data”编码成消息,每个控件对应消息的一部分.请求方式必须是post
- oenctype=“text/plain"纯文本形式进行编码的
服务端可以使用FormFile(“name”)获取到上传的文件
main.go
package main
import (
"html/template"
"io/ioutil"
"net/http"
"strings"
)
func welcome(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("demo/view/index.html")
t.Execute(w, nil)
}
func upload(w http.ResponseWriter, r *http.Request) {
fileName := r.FormValue("name")
//获取到文件,文件名
file, fileHeader, _ := r.FormFile("file")
b, _ := ioutil.ReadAll(file)
//获取文件名扩展名
s := fileHeader.Filename[strings.LastIndex(fileHeader.Filename, "."):]
//文件名,[]byte,模式
ioutil.WriteFile("D:/"+fileName+s, b, 0777)
t, _ := template.ParseFiles("demo/view/success.html")
t.Execute(w, nil)
}
func main() {
server := http.Server{Addr: ":8090"}
http.HandleFunc("/", welcome)
http.HandleFunc("/upload", upload)
server.ListenAndServe()
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件上传</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
文件名:<input type="text" name="name"/><br/>
文件:<input type="file" name="file"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
文件下载
文件下载总体步骤
- 客户端向服务端发起请求,请求参数包含要下载文件的名称
- 服务器接收到客户端请求后把文件设置到响应对象中,响应给客户端浏览器
下载时需要设置的响应头信息
-
content-Type:内容MIME类型
application/octet-stream 任意类型
-
Content-Disposition:客户端对内容的操作方式
inline 默认值,表示浏览器能解析就解析,不能解析下载
attachment;filename=下载时显示的文件名,客户端浏览器恒下载
mian.go
package main
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
"strings"
)
func welcome(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("demo/view/index.html")
t.Execute(w, nil)
}
func download(w http.ResponseWriter, r *http.Request) {
filename := r.FormValue("fileName")
f, err := ioutil.ReadFile("D:/gofile/" + filename)
if err != nil {
fmt.Fprintln(w, "文件下载失败", err)
return
}
//设置响应头
h := w.Header()
h.Set("Content-Type", "application/octet-stream")
h.Set("Content-Disposition", "attachment;filename="+filename)
w.Write(f)
}
func main() {
server := http.Server{Addr: ":8090"}
http.HandleFunc("/", welcome)
http.HandleFunc("/download", download)
server.ListenAndServe()
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件下载</title>
</head>
<body>
<a href="download?fileName=abc.png">下载</a>
</body>
</html>