63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package utils
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/google/uuid"
|
|
"trle5.xyz/upscayl-server/configs"
|
|
)
|
|
|
|
func SaveUpload(r *http.Request) (string, string, error) {
|
|
taskID := uuid.NewString()
|
|
|
|
err := os.MkdirAll(configs.InputDir, os.ModePerm)
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("failed to create directory: %w", err)
|
|
}
|
|
|
|
dst, err := os.Create(filepath.Join(configs.InputDir, taskID + ".temp"))
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("failed to create file: %w", err)
|
|
}
|
|
defer dst.Close()
|
|
|
|
hash := sha256.New()
|
|
mw := io.MultiWriter(dst, hash)
|
|
|
|
link := r.FormValue("link")
|
|
file, _, err := r.FormFile("file")
|
|
if link != "" {
|
|
log.Printf("Get [%s] task file from link [%s]", taskID, link)
|
|
// Download the file from the link
|
|
resp, err := http.Get(link)
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("failed to download file: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
_, err = io.Copy(mw, resp.Body)
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("failed to copy file: %w", err)
|
|
}
|
|
} else if err == nil {
|
|
log.Printf("Get [%s] task file from form file", taskID)
|
|
defer file.Close()
|
|
|
|
_, err = io.Copy(mw, file)
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("failed to copy file: %w", err)
|
|
}
|
|
} else {
|
|
return "", "", fmt.Errorf("failed to get link or file: %w", err)
|
|
}
|
|
|
|
return taskID, hex.EncodeToString(hash.Sum(nil)), nil
|
|
}
|