go 语言代码
package main
import (
"io"
"log"
"net/http"
"os"
)
func uploadOne(w http.ResponseWriter, r *http.Request) {
//判断请求方式
if r.Method == "POST" {
//设置内存大小
r.ParseMultipartForm(32 << 20)
w.Write([]byte("ok."))
//获取上传的第一个文件
file, header, err := r.FormFile("file")
// 判断文件有效性
if err != nil {
w.Write([]byte("no..."))
} else {
defer file.Close()
//创建上传目录
os.Mkdir("./upload", os.ModePerm)
//创建上传文件
cur, err := os.Create("./upload/" + header.Filename)
if err != nil {
println(err.Error())
} else {
defer cur.Close()
//把上传文件数据拷贝到我们新建的文件
io.Copy(cur, file)
w.Write([]byte("ok"))
}
}
}
}
func uploadMore(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
//设置内存大小
r.ParseMultipartForm(32 << 20)
//获取上传的文件组
files := r.MultipartForm.File["file"]
len := len(files)
for i := 0; i < len; i++ {
//打开上传文件
file, err := files[i].Open()
if err != nil {
log.Fatal(err)
} else {
defer file.Close()
//创建上传目录
os.Mkdir("./upload", os.ModePerm)
//创建上传文件
cur, err := os.Create("./upload/" + files[i].Filename)
if err != nil {
log.Fatal(err)
} else {
defer cur.Close()
io.Copy(cur, file)
}
}
}
}
}
func main() {
http.HandleFunc("/uploadMore", uploadMore)
http.HandleFunc("/uploadOne", uploadOne)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal(err)
}
}
前端 html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form
action="http://127.0.0.1:9090/uploadMore"
method="post"
enctype="multipart/form-data">
<div>
文件:<input type="file" name="file" value="">
</div>
<div>
文件:<input type="file" name="file" value="">
</div>
<input type="submit" value="提交">
<div>提交</div>
</form>
</body>
</html>