package zciyon

import (
	"bufio"
	"fmt"
	_ "image/png"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
)

func SaveUploadFile(path string, file *multipart.FileHeader) (map[string]any, error) {
	if FileExist(CiyWebDir+"/ud/"+path) == nil {
		return nil, fmt.Errorf("文件已存在")
	}
	err := DirMake(CiyWebDir + "/ud/" + filepath.Dir(path))
	if err != nil {
		return nil, fmt.Errorf("创建目录失败:%v", err)
	}
	srcF, err := file.Open()
	if err != nil {
		return nil, fmt.Errorf("打开临时文件失败:%v[%v]", err, file.Filename)
	}
	defer srcF.Close()
	reader := bufio.NewReader(srcF)
	dstF, err := os.OpenFile(CiyWebDir+"/ud/"+path, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return nil, fmt.Errorf("创建文件失败:" + path)
	}
	defer dstF.Close()
	writer := bufio.NewWriter(dstF)
	_, err = io.Copy(writer, reader)
	if err != nil {
		return nil, fmt.Errorf("拷贝文件失败:" + path)
	}
	ret := map[string]any{}
	ret["url"] = "/" + path
	return ret, nil
}
