ZGGSONG 2 years ago
parent 62f81bb049
commit 563d529708

4
.gitignore vendored

@ -7,4 +7,6 @@ receive-files
*.log
.out
.out
/upload

@ -1,3 +1,7 @@
module receive-files
go 1.18
require github.com/fsnotify/fsnotify v1.5.4
require golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect

@ -0,0 +1,4 @@
github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI=
github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

@ -2,6 +2,7 @@ package main
import (
"fmt"
"github.com/fsnotify/fsnotify"
"io"
"log"
"net/http"
@ -9,13 +10,19 @@ import (
"strconv"
)
var (
count = 0
path = "upload"
)
func main() {
port := 7201
mux := http.NewServeMux()
mux.HandleFunc("/upload", handler2)
os.Mkdir(path, 0755)
// 监听目录下文件
go listenFloder("./upload")
go listenFloder()
fmt.Printf("开启服务 监听端口 %v...\n", port)
err := http.ListenAndServe(":"+strconv.Itoa(port), mux)
@ -24,8 +31,63 @@ func main() {
}
}
func listenFloder(path string) {
func listenFloder() {
//创建一个监控对象
watch, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watch.Close()
//添加要监控的对象,文件或文件夹
err = watch.Add(path)
if err != nil {
log.Fatal(err)
}
//我们另启一个goroutine来处理监控对象的事件
go func() {
for {
if count > 1 {
go func() {
fmt.Printf("%d\n", count)
}()
}
select {
case ev := <-watch.Events:
{
//判断事件发生的类型如下5种
// Create 创建
// Write 写入
// Remove 删除
// Rename 重命名
// Chmod 修改权限
if ev.Op&fsnotify.Create == fsnotify.Create {
count++
log.Println("创建文件 : ", ev.Name)
}
if ev.Op&fsnotify.Write == fsnotify.Write {
log.Println("写入文件 : ", ev.Name)
}
if ev.Op&fsnotify.Remove == fsnotify.Remove {
log.Println("删除文件 : ", ev.Name)
}
if ev.Op&fsnotify.Rename == fsnotify.Rename {
log.Println("重命名文件 : ", ev.Name)
}
if ev.Op&fsnotify.Chmod == fsnotify.Chmod {
log.Println("修改权限 : ", ev.Name)
}
}
case err := <-watch.Errors:
{
log.Println("error : ", err)
return
}
}
}
}()
//循环
select {}
}
func handler2(w http.ResponseWriter, r *http.Request) {
@ -38,7 +100,7 @@ func handler2(w http.ResponseWriter, r *http.Request) {
}
defer formFile.Close()
// 创建保存文件
destFile, err := os.Create("./upload/" + fn)
destFile, err := os.Create("./" + path + "/" + fn)
if err != nil {
log.Printf("Create failed: %s\n", err)
return

Loading…
Cancel
Save