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.
 
 
 
 
 
 

39 lines
797 B

package storage
import (
"crypto/rand"
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
)
func SaveImage(file multipart.File, header *multipart.FileHeader, uploadDir string) (string, error) {
if err := os.MkdirAll(uploadDir, 0755); err != nil {
return "", fmt.Errorf("create upload dir: %w", err)
}
ext := filepath.Ext(header.Filename)
if ext == "" {
ext = ".png"
}
var buf [16]byte
if _, err := io.ReadFull(rand.Reader, buf[:]); err != nil {
return "", err
}
filename := fmt.Sprintf("%x%s", buf, ext)
dst, err := os.Create(filepath.Join(uploadDir, filename))
if err != nil {
return "", fmt.Errorf("create file: %w", err)
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
return "", fmt.Errorf("write file: %w", err)
}
return filename, nil
}