forked from albertba/Advertisement_Panel
39 lines
991 B
Go
39 lines
991 B
Go
package api
|
|
|
|
import (
|
|
"Advertisement_Panel/db"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
func UploadHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != "POST" {
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
file, header, err := r.FormFile("image") // "image" is the name of the file input
|
|
if err != nil {
|
|
http.Error(w, "Error retrieving file", http.StatusBadRequest)
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
dst, err := os.Create("./uploads/" + header.Filename)
|
|
if err != nil {
|
|
http.Error(w, "Error creating file on server", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer dst.Close()
|
|
|
|
if _, err := io.Copy(dst, file); err != nil {
|
|
http.Error(w, "Error saving file", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
fmt.Fprint(w, "<script>location.href = '/admin/'</script>")
|
|
fmt.Fprintf(w, "Image uploaded successfully: %s", header.Filename)
|
|
db.DB.Exec("INSERT INTO images (path, spice_level) VALUES ($1, $2)", "/uploads/"+header.Filename, 0)
|
|
}
|