Thumbnail upload

This commit is contained in:
2025-03-13 23:40:31 +02:00
parent 75be79c6cf
commit cfea8dcb4f
2 changed files with 53 additions and 3 deletions

2
.gitignore vendored
View File

@@ -3,3 +3,5 @@ out
.env .env
assets/ assets/
samples/ samples/
.idea

View File

@@ -2,6 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"io"
"net/http" "net/http"
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth" "github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth"
@@ -28,10 +29,57 @@ func (cfg *apiConfig) handlerUploadThumbnail(w http.ResponseWriter, r *http.Requ
return return
} }
fmt.Println("uploading thumbnail for video", videoID, "by user", userID) fmt.Println("uploading thumbnail for video", videoID, "by user", userID)
// TODO: implement the upload here var maxMemory int64
maxMemory = 10 << 20
respondWithJSON(w, http.StatusOK, struct{}{}) err = r.ParseMultipartForm(maxMemory)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't parse multipart form", err)
}
image, header, err := r.FormFile("thumbnail")
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't get file", err)
}
mediaType := header.Header.Get("Content-Type")
imageData, err := io.ReadAll(image)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't read image", err)
}
video, err := cfg.db.GetVideo(videoID)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't find video", err)
}
if video.UserID != userID {
respondWithError(w, http.StatusUnauthorized, "You are not authorized to upload this video", err)
}
thumb := thumbnail{
data: imageData,
mediaType: mediaType,
}
videoThumbnails[videoID] = thumb
url := "http://localhost:" + cfg.port + "/api/thumbnails/" + videoID.String()
video.ThumbnailURL = &url
err = cfg.db.UpdateVideo(video)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't update video", err)
}
video, err = cfg.db.GetVideo(videoID)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't find video", err)
}
respondWithJSON(w, http.StatusOK, video)
} }