1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
const index string = "<!DOCTYPE >\n" +
"<html>\n" +
"<head>\n" +
" <title>upload</title>\n" +
"</head>\n" +
"\n" +
"<body>\n" +
"<form enctype=\"multipart/form-data\" method=\"post\" action=\"/upload/file\">\n" +
" 图片<input type=\"file\" name=\"one\"/>\n" +
" <input type=\"submit\" value=\"上传\"/>\n" +
"</form>\n" +
"</body>"
var temp = "/test"
func main() {
mux := http.NewServeMux()
os.MkdirAll(temp, os.ModePerm)
mux.HandleFunc("/upload/file", uploadHandle)
mux.HandleFunc("/upload/index", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Type", "text/html; charset=utf-8")
io.WriteString(writer, index)
})
fs := http.FileServer(http.Dir(temp))
mux.Handle("/", fs)
log.Fatal(http.ListenAndServe(":60000", mux))
}
func uploadHandle(w http.ResponseWriter, r *http.Request) {
// 根据字段名获取表单文件
formFile, header, err := r.FormFile("one")
if err != nil {
log.Printf("Get form file failed: %s\n", err)
return
}
defer formFile.Close()
// 创建保存文件
destFile, err := os.Create(temp + "/" + header.Filename)
fmt.Println(temp + "/" + header.Filename)
if err != nil {
log.Printf("Create failed: %s\n", err)
return
}
defer destFile.Close()
// 读取表单文件,写入保存文件
_, err = io.Copy(destFile, formFile)
if err != nil {
log.Printf("Write file failed: %s\n", err)
return
}
}
|