Browse Source

增加发送文件,发送zip功能

master
xyiege 5 months ago
parent
commit
a810a6cade
  1. 119
      aufs/core/send.go
  2. 103
      aufs/core/sendzip.go
  3. 2
      aufs/main.go
  4. 26
      vue/afvue/src/views/Sfilecompare.vue

119
aufs/core/send.go

@ -0,0 +1,119 @@
package core
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"aufs/util"
"github.com/schollz/progressbar/v3"
)
// 发送文件
func SendFiles(filePath string, url string) error {
filePath = filepath.ToSlash(filePath)
fileInfo, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("file [%s] not exist", filePath)
}
return fmt.Errorf("file [%s] error: %w", filePath, err)
}
if fileInfo.IsDir() {
return postDirectory(filePath, url)
}
return postFile(filePath, path.Base(filePath), url)
}
// 传送文件夹
func postDirectory(dirPath string, url string) error {
files, err := util.GetDirFilePaths(dirPath, false)
if err != nil {
return err
}
fmt.Println("\nAll files in folder:")
for _, file := range files {
fmt.Println(file)
}
var confirm string
fmt.Print("\nTransfer all files? [Y/N] ")
fmt.Scanln(&confirm)
if strings.ToLower(confirm) != "y" {
fmt.Print("\nCancel send all files ")
return nil
}
for _, file := range files {
fileName, _ := filepath.Rel(dirPath, file)
fileName = filepath.Join(filepath.Base(dirPath), fileName)
err := postFile(file, fileName, url)
if err != nil {
return err
}
}
fmt.Printf("Send folder %s success.\n", dirPath)
return nil
}
// 传送文件
func postFile(filePath string, filename string, url string) error {
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
part, err := writer.CreateFormFile("file", filepath.ToSlash(filename))
if err != nil {
return err
}
fileInfo, _ := file.Stat()
bar := progressbar.DefaultBytes(
fileInfo.Size(),
fmt.Sprintf("Uploading [%s]", filename),
)
_, err = io.Copy(io.MultiWriter(part, bar), file)
if err != nil {
return err
}
err = writer.Close()
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, url, payload)
if err != nil {
return err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("upload failed with status code: %d", resp.StatusCode)
}
return nil
}

103
aufs/core/sendzip.go

@ -0,0 +1,103 @@
package core
import (
"fmt"
"aufs/config"
"aufs/util"
"net"
"net/http"
"path"
"path/filepath"
"strings"
"time"
)
func SendZip(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
// 选择文件,并生成zip包
// 文件
zipfarr := r.Form["sfiles"]
// 服务器ip地址
serip := r.Form["serverip"]
if serip[0] == "" {
http.Error(w, "remote server ip is blank!", http.StatusInternalServerError)
return
}
tpath := ""
// 选中的路径,可以为空
wtculpath := r.Form["curpath"]
if wtculpath != nil {
tpath = util.Base64dec(wtculpath[0])
}
// 实际路径
realFilePath := filepath.Join(config.G.FilePath, tpath)
// zip 文件名
zpFileName := "BIU_" + time.Now().Format("20060102_150405") + ".zip"
// 创建zip 异步?
taskId := make(chan string)
go func() {
util.CompressToZip(zpFileName, realFilePath, zipfarr)
taskId <- "arcok"
// fmt.Fprintln(w, "create archive:", err)
}()
// go util.CompressToZip(zpFileName, realFilePath, zipfarr)
fmt.Println("archive is createding...")
// 当前运行的目录
// ZIP 文件的实际路径
ziprl := path.Join("./sync_zips/", zpFileName)
// zip 创建成功后
rest := <-taskId
// 有压缩包 才可以操作
if strings.EqualFold(strings.ToLower(rest), "arcok") {
fmt.Println("archive is sending...")
// 创建udp 渠道发送数据
message := fmt.Sprintf("%s%s%s", config.G.DeviceName, "|", "sender")
UdpSendFile(serip[0], ziprl, zpFileName, message, w)
} else {
fmt.Println("archive is not exist!!!")
}
// 执行完 跳转到 首页
http.Redirect(w, r, "/", http.StatusFound)
}
// udp 模式发送文件
/*
* serip 服务器ip,
* absfilepath 发送文件的实际路径,
* fname 文件名
* message 携带部分信息的消息
* http.ResponseWriter
*/
func UdpSendFile(serip string, absfilepath string, fname string, message string, w http.ResponseWriter) {
// 1、获取udp addr
remoteAddr, err := net.ResolveUDPAddr("udp", serip+":9099")
if err != nil {
return
}
// 2、 监听端口
conn, err := net.DialUDP("udp", nil, remoteAddr)
if err != nil {
return
}
defer conn.Close()
// 3、在端口发送数据
// message := fmt.Sprintf("%s%s%s", config.G.DeviceName, "|", "sender")
// 向链接通道发送数据 数据包头
conn.Write([]byte(message))
// 发送文件
go func() {
err := util.SendFiles(absfilepath, fmt.Sprintf("http://%s/rc", remoteAddr))
if err != nil {
fmt.Printf("Send file to %s error: %s\n", remoteAddr, err)
}
}()
}

2
aufs/main.go

@ -33,7 +33,7 @@ func startWeb() {
// 文件接收
// http.HandleFunc("/rc", core.ReceiveHandler)
// 发送zip文件
// http.HandleFunc("/sendZip", core.SendZip)
http.HandleFunc("/sendZip", core.SendZip)
// 系统监控
http.HandleFunc("/sysinfo", core.SysMonitor)
//保存监听的服务器

26
vue/afvue/src/views/Sfilecompare.vue

@ -17,7 +17,7 @@
</div>
<div class="sflist">
<form @submit.prevent="submitForm(index)" method="post">
<form @submit.prevent="submitForm" method="post" ref="fsform">
<ul>
<li v-for="(item, index) in fsclist" :key="item" :data-index="index">
<input type="checkbox" :value="item.path" class="sfchkbox" :name="'fsbox' + index" :ref="'fsbox' + index"/>
@ -27,7 +27,8 @@
</ul>
<div class="fbdiv" v-if="fsclist.length > 0">
<button class="fbtn" title="sync_btn">同步选中的文件</button>
<input type="hidden" name="curpath" :value="fspath" />
<button class="fbtn">同步选中的文件</button>
</div>
</form>
</div>
@ -125,8 +126,6 @@ export default {
if (this.isMenuVisible) {
this.hideMenu()
}
})
// 使
SerlistInUsing().then(res => {
@ -307,9 +306,22 @@ export default {
this.hideMenu(); //
},
//
submitForm(index){
let form = document.getElementsByName('fsbox' + index)
console.log(form,"form")
submitForm(){
// checkbox
let chkbox = document.getElementsByClassName('sfchkbox')
for(let i=0;i<chkbox.length;i++){
if(chkbox[i].checked){
//
let rv = chkbox[i].value
this.selectedFiles.push(rv)
}
}
let srt = this.selectedFiles.join(',')
console.log(srt,"srt")
//
let curpath = this.fspath
},
//

Loading…
Cancel
Save