You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.0 KiB
86 lines
2.0 KiB
package task
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strconv"
|
|
"time"
|
|
|
|
"task-track-backend/model"
|
|
"task-track-backend/pkg/database"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func (h *TaskHandler) AddTaskAttachment(c *gin.Context) {
|
|
// 获取任务ID
|
|
taskIDStr := c.Param("id")
|
|
taskID, err := strconv.ParseUint(taskIDStr, 10, 32)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的任务ID"})
|
|
return
|
|
}
|
|
|
|
// 获取上传的用户ID
|
|
userIDStr := c.PostForm("user_id")
|
|
if userIDStr == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "用户ID不能为空"})
|
|
return
|
|
}
|
|
|
|
userID, err := strconv.ParseUint(userIDStr, 10, 32)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID"})
|
|
return
|
|
}
|
|
|
|
// 处理文件上传
|
|
file, err := c.FormFile("file")
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败"})
|
|
return
|
|
}
|
|
|
|
db := database.GetDB()
|
|
|
|
// 检查任务是否存在
|
|
var existingTask model.Task
|
|
if err := db.First(&existingTask, uint(taskID)).Error; err != nil {
|
|
if err.Error() == "record not found" {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "任务不存在"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询任务失败"})
|
|
return
|
|
}
|
|
|
|
// 生成文件名和路径
|
|
timestamp := time.Now().UnixNano()
|
|
fileName := file.Filename
|
|
filePath := fmt.Sprintf("uploads/%d_%s", timestamp, fileName)
|
|
|
|
// 保存文件
|
|
if err := c.SaveUploadedFile(file, filePath); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存文件失败"})
|
|
return
|
|
}
|
|
|
|
// 创建附件记录
|
|
attachment := model.TaskAttachment{
|
|
TaskID: uint(taskID),
|
|
FileName: fileName,
|
|
FilePath: filePath,
|
|
FileSize: file.Size,
|
|
FileType: filepath.Ext(fileName),
|
|
UploadedBy: uint(userID),
|
|
CreatedAt: time.Now(),
|
|
}
|
|
|
|
if err := db.Create(&attachment).Error; err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "创建附件记录失败"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, attachment)
|
|
}
|
|
|