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.
71 lines
1.6 KiB
71 lines
1.6 KiB
package task
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// UploadFileResponse 上传文件响应结构
|
|
type UploadFileResponse struct {
|
|
FileName string `json:"file_name"`
|
|
FilePath string `json:"file_path"`
|
|
FileSize int64 `json:"file_size"`
|
|
FileType string `json:"file_type"`
|
|
}
|
|
|
|
func (h *TaskHandler) UploadFile(c *gin.Context) {
|
|
// 处理文件上传
|
|
file, err := c.FormFile("file")
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败"})
|
|
return
|
|
}
|
|
|
|
// 验证文件大小 (限制为 10MB)
|
|
maxSize := int64(10 * 1024 * 1024)
|
|
if file.Size > maxSize {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "文件大小超过限制"})
|
|
return
|
|
}
|
|
|
|
// 验证文件类型
|
|
allowedTypes := []string{".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt"}
|
|
fileExt := filepath.Ext(file.Filename)
|
|
isAllowed := false
|
|
for _, allowedType := range allowedTypes {
|
|
if fileExt == allowedType {
|
|
isAllowed = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !isAllowed {
|
|
c.JSON(http.StatusBadRequest, 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
|
|
}
|
|
|
|
// 返回文件信息
|
|
response := UploadFileResponse{
|
|
FileName: fileName,
|
|
FilePath: filePath,
|
|
FileSize: file.Size,
|
|
FileType: fileExt,
|
|
}
|
|
|
|
c.JSON(http.StatusOK, response)
|
|
}
|
|
|