From fffdc7fd5e4b9ad7921f6a75521ccf46af564ad4 Mon Sep 17 00:00:00 2001 From: CorrectRoadH Date: Thu, 18 Jan 2024 12:23:27 +0800 Subject: [PATCH] fix: fix upload folder fail (#1614) Signed-off-by: CorrectRoadH --- route/v2.go | 2 +- service/file_upload.go | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/route/v2.go b/route/v2.go index d324920..10daefc 100644 --- a/route/v2.go +++ b/route/v2.go @@ -120,7 +120,7 @@ func InitV2Router() http.Handler { // jump validate when upload file // because file upload can't pass validate // issue: https://github.com/deepmap/oapi-codegen/issues/514 - return strings.Contains(c.Request().URL.Path, "file/upload") + return strings.Contains(c.Request().Header[echo.HeaderContentType][0], "multipart/form-data") }, Options: openapi3filter.Options{AuthenticationFunc: openapi3filter.NoopAuthenticationFunc}, })) diff --git a/service/file_upload.go b/service/file_upload.go index 7654c2c..df217ce 100644 --- a/service/file_upload.go +++ b/service/file_upload.go @@ -8,7 +8,9 @@ import ( "path/filepath" "sync" + "github.com/IceWhaleTech/CasaOS-Common/utils/logger" "github.com/labstack/echo/v4" + "go.uber.org/zap" ) type FileInfo struct { @@ -76,7 +78,11 @@ func (s *FileUploadService) UploadFile( // uploaded file is folder folderPath := filepath.Dir(path + "/" + relativePath) if _, err := os.Stat(folderPath); os.IsNotExist(err) { - os.MkdirAll(folderPath, os.ModePerm) + err := os.MkdirAll(folderPath, os.ModePerm) + if err != nil { + s.lock.Unlock() + return err + } } } @@ -124,8 +130,7 @@ func (s *FileUploadService) UploadFile( } defer src.Close() - buf := make([]byte, int(currentChunkSize)) - _, err = io.CopyBuffer(file, src, buf) + _, err = io.Copy(file, src) if err != nil { fmt.Println(err) @@ -142,9 +147,17 @@ func (s *FileUploadService) UploadFile( // handle file after write all chunk if fileInfo.uploadedChunkNum == totalChunks { - file.Close() - os.Rename(path+"/"+fileName+".tmp", path+"/"+fileName) + err := file.Close() + if err != nil { + s.lock.Unlock() + logger.Error("close file error: ", zap.Error(err)) + } + err = os.Rename(path+"/"+relativePath+".tmp", path+"/"+relativePath) + if err != nil { + s.lock.Unlock() + logger.Error("rename file error: ", zap.Error(err)) + } // remove upload status info after upload complete s.uploadStatus.Delete(identifier) }