Browse Source

change download

master
godo 10 months ago
parent
commit
e77cbbb002
  1. 28
      godo/localchat/filedown.go
  2. 27
      godo/localchat/getfiles.go

28
godo/localchat/filedown.go

@ -53,6 +53,16 @@ func downloadFiles(msg UdpMessage) error {
return fmt.Errorf("server returned status code: %v, body: %s", resp.StatusCode, body) return fmt.Errorf("server returned status code: %v, body: %s", resp.StatusCode, body)
} }
// 处理响应中的文件
if err := handleResponse(resp.Body, msg.IP); err != nil {
log.Fatalf("Failed to handle response: %v", err)
}
fmt.Println("Files downloaded successfully")
return nil
}
func handleResponse(reader io.Reader, ip string) error {
// 接收文件的目录 // 接收文件的目录
baseDir, err := libs.GetOsDir() baseDir, err := libs.GetOsDir()
if err != nil { if err != nil {
@ -69,17 +79,6 @@ func downloadFiles(msg UdpMessage) error {
return fmt.Errorf("failed to create receive directory") return fmt.Errorf("failed to create receive directory")
} }
} }
// 处理响应中的文件
if err := handleResponse(resp.Body, receiveDir, msg.IP); err != nil {
log.Fatalf("Failed to handle response: %v", err)
}
fmt.Println("Files downloaded successfully")
return nil
}
func handleResponse(reader io.Reader, saveDir string, ip string) error {
body, err := io.ReadAll(reader) body, err := io.ReadAll(reader)
if err != nil { if err != nil {
return fmt.Errorf("failed to read response body: %v", err) return fmt.Errorf("failed to read response body: %v", err)
@ -90,17 +89,16 @@ func handleResponse(reader io.Reader, saveDir string, ip string) error {
if err := json.Unmarshal(body, &fileList); err != nil { if err := json.Unmarshal(body, &fileList); err != nil {
return fmt.Errorf("failed to unmarshal file list: %v", err) return fmt.Errorf("failed to unmarshal file list: %v", err)
} }
log.Printf("Received file list: %v", fileList) log.Printf("Received file list: %v", fileList)
for _, file := range fileList { for _, file := range fileList {
checkpath := filepath.Join(saveDir, file.WritePath) checkpath := filepath.Join(receiveDir, file.WritePath)
if err := os.MkdirAll(checkpath, 0755); err != nil { if err := os.MkdirAll(checkpath, 0755); err != nil {
return fmt.Errorf("failed to create directory: %v", err) return fmt.Errorf("failed to create directory: %v", err)
} }
if !file.IsDir { if !file.IsDir {
if err := downloadFile(file.Path, checkpath, ip); err != nil { go downloadFile(file.Path, checkpath, ip)
return fmt.Errorf("failed to download file: %v", err)
}
} }
} }

27
godo/localchat/getfiles.go

@ -41,20 +41,24 @@ type FileItem struct {
Filename string `json:"filename"` Filename string `json:"filename"`
WritePath string `json:"writePath"` WritePath string `json:"writePath"`
} }
type FileList struct {
Files []string `json:"fileList"`
}
func HandleGetFiles(w http.ResponseWriter, r *http.Request) { func HandleGetFiles(w http.ResponseWriter, r *http.Request) {
//log.Printf("=====Received request: %v", r)
if r.Method != "POST" { if r.Method != "POST" {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return return
} }
var fileList []string var fileList FileList
err := json.NewDecoder(r.Body).Decode(&fileList) err := json.NewDecoder(r.Body).Decode(&fileList)
if err != nil { if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest) http.Error(w, "Invalid request body", http.StatusBadRequest)
return return
} }
log.Printf("Received file list: %v", fileList) //log.Printf("=====Received file list: %v", fileList)
defer r.Body.Close() defer r.Body.Close()
baseDir, err := libs.GetOsDir() baseDir, err := libs.GetOsDir()
@ -67,7 +71,7 @@ func HandleGetFiles(w http.ResponseWriter, r *http.Request) {
// 用于存储文件列表 // 用于存储文件列表
var files []FileItem var files []FileItem
for _, filePath := range fileList { for _, filePath := range fileList.Files {
fp := filepath.Join(baseDir, filePath) fp := filepath.Join(baseDir, filePath)
fileInfo, err := os.Stat(fp) fileInfo, err := os.Stat(fp)
@ -75,15 +79,9 @@ func HandleGetFiles(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("Failed to stat file: %v", err), http.StatusInternalServerError) http.Error(w, fmt.Sprintf("Failed to stat file: %v", err), http.StatusInternalServerError)
return return
} }
writePath := calculateWritePath(fp, baseDir) //writePath := calculateWritePath(fp, baseDir)
if fileInfo.IsDir() { if fileInfo.IsDir() {
files = append(files, FileItem{ if err := walkDirectory(fp, &files, filepath.Base(fp)); err != nil {
Path: fp,
IsDir: true,
Filename: filepath.Base(fp),
WritePath: writePath,
})
if err := walkDirectory(fp, &files, writePath); err != nil {
http.Error(w, fmt.Sprintf("Failed to serve directory: %v", err), http.StatusInternalServerError) http.Error(w, fmt.Sprintf("Failed to serve directory: %v", err), http.StatusInternalServerError)
return return
} }
@ -93,7 +91,7 @@ func HandleGetFiles(w http.ResponseWriter, r *http.Request) {
Path: fp, Path: fp,
IsDir: false, IsDir: false,
Filename: filepath.Base(fp), Filename: filepath.Base(fp),
WritePath: writePath, WritePath: "",
}) })
} }
} }
@ -104,6 +102,7 @@ func HandleGetFiles(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Failed to marshal file list", http.StatusInternalServerError) http.Error(w, "Failed to marshal file list", http.StatusInternalServerError)
return return
} }
log.Printf("Sending file list: %v", string(jsonData))
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write(jsonData) w.Write(jsonData)
@ -126,9 +125,9 @@ func walkDirectory(rootPath string, files *[]FileItem, writePath string) error {
relativePath, err := filepath.Rel(rootPath, path) relativePath, err := filepath.Rel(rootPath, path)
if err != nil { if err != nil {
log.Printf("Failed to calculate relative path: %v", err) log.Printf("Failed to calculate relative path: %v", err)
return fmt.Errorf("Failed to calculate relative path") return fmt.Errorf("failed to calculate relative path")
} }
currentWritePath := filepath.Join(writePath, filepath.Dir(relativePath)) currentWritePath := filepath.Join(writePath, filepath.Base(relativePath))
*files = append(*files, FileItem{ *files = append(*files, FileItem{
Path: path, Path: path,
IsDir: isDir, IsDir: isDir,

Loading…
Cancel
Save