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
66
67
68
69
70
|
package main
import (
"fmt"
"io"
"net/http"
"os"
"path"
)
func main() {
http.HandleFunc("/upload", upload)
_ = http.ListenAndServe(":8888", nil)
}
// 上传文件
func upload(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && r.ParseForm() == nil {
// 接收上传文件的参数
formFile, fileHeader, err := r.FormFile("file")
if formFile == nil {
http.Error(w,"上传的文件不能为空!",http.StatusInternalServerError)
return
}
if err != nil {
http.Error(w,err.Error(),http.StatusInternalServerError)
return
}
// 延迟关闭文件
defer formFile.Close()
// 获取上传文件的名称
filename := fileHeader.Filename
fmt.Printf("文件名称: %s \n",filename)
// 获取文件的后缀
ext := path.Ext(filename)
fmt.Printf("文件后缀: %s \n",ext)
// 创建新文件,如果同名文件存在,则会清空
pathName := "public/img"
if !pathExist(pathName) {
err := os.MkdirAll(pathName, os.ModePerm)
if err != nil {
http.Error(w,"创建目录失败: "+ err.Error(),http.StatusInternalServerError)
return
}
}
newFile, err := os.Create(pathName +"/"+ filename)
if err != nil {
http.Error(w,"创建文件失败: "+ err.Error(),http.StatusInternalServerError)
return
}
defer newFile.Close()
// 将formFile复制到newFile,从而实现上传的功能
written, err := io.Copy(newFile, formFile)
fmt.Printf("上传结果: %d \n",written)
if err != nil {
http.Error(w,"文件上传失败: "+ err.Error(),http.StatusInternalServerError)
return
}
w.Write([]byte("文件上传成功!"))
}
return
}
// 判断目录是否存在
func pathExist(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
|