Files
bj_power/bj_power_mes/internal/handler/upload.go
T

78 lines
2.1 KiB
Go
Raw Normal View History

package handler
import (
"crypto/rand"
"encoding/hex"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
// saveUploadFile 保存上传文件(工艺图纸PDF / 巡检照片),返回生成的相对文件名(含日期子目录)
func saveUploadFile(r *http.Request, field, dir string) (string, error) {
sub := time.Now().Format("2006-01-02")
full := filepath.Join(dir, sub)
if err := os.MkdirAll(full, 0o755); err != nil {
return "", err
}
file, header, err := r.FormFile(field)
if err != nil {
return "", err
}
defer file.Close()
ext := strings.ToLower(filepath.Ext(header.Filename))
if ext == "" {
ext = ".bin"
}
name := time.Now().Format("20060102150405") + "_" + randHex(6) + ext
dst, err := os.Create(filepath.Join(full, name))
if err != nil {
return "", err
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
return "", err
}
return filepath.ToSlash(filepath.Join(sub, name)), nil
}
func randHex(n int) string {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)[:n*2]
}
// serveUploadFile 下发上传目录中的文件(仅允许 单层日期子目录/文件名,防路径穿越)
func serveUploadFile(w http.ResponseWriter, r *http.Request, dir, name string) {
name = strings.TrimSpace(name)
clean := filepath.Clean(filepath.FromSlash(name))
if clean == "." || clean == ".." ||
strings.HasPrefix(clean, ".."+string(filepath.Separator)) ||
filepath.IsAbs(clean) || strings.ContainsRune(name, '\x00') {
http.Error(w, "非法文件名", http.StatusBadRequest)
return
}
f, err := os.Open(filepath.Join(dir, clean))
if err != nil {
http.Error(w, "文件不存在", http.StatusNotFound)
return
}
defer f.Close()
ct := "application/octet-stream"
base := strings.ToLower(clean)
switch {
case strings.HasSuffix(base, ".pdf"):
ct = "application/pdf"
case strings.HasSuffix(base, ".jpg"), strings.HasSuffix(base, ".jpeg"):
ct = "image/jpeg"
case strings.HasSuffix(base, ".png"):
ct = "image/png"
}
w.Header().Set("Content-Type", ct)
http.ServeContent(w, r, name, time.Time{}, f)
}