Implement file upload for replies

This commit is contained in:
Dominic Ferrando
2025-04-18 15:41:29 -04:00
parent 00c8057b5b
commit a80a7a4dba
6 changed files with 188 additions and 130 deletions
+1
View File
@@ -1,3 +1,4 @@
internal/database/comfychan.db
**/*_templ.go
tmp
web/static/img/posts
+2 -2
View File
@@ -118,8 +118,8 @@ func PutThread(db *sql.DB, boardSlug string, subject string, body string, mediaP
return nil
}
func PutPost(db *sql.DB, threadId int, body string) error {
_, err := db.Exec(`INSERT INTO posts (thread_id, body) VALUES (?, ?)`, threadId, body)
func PutPost(db *sql.DB, threadId int, body string, mediaPath string) error {
_, err := db.Exec(`INSERT INTO posts (thread_id, body, media_path) VALUES (?, ?, ?)`, threadId, body, mediaPath)
if err != nil {
return err
}
+57 -20
View File
@@ -2,9 +2,11 @@ package main
import (
"database/sql"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
@@ -17,6 +19,8 @@ import (
_ "github.com/mattn/go-sqlite3"
)
const FILE_MEM_LIMIT int64 = 10 << 20
var dev = true
func disableCacheInDevMode(next http.Handler) http.Handler {
@@ -29,6 +33,24 @@ func disableCacheInDevMode(next http.Handler) http.Handler {
})
}
func savePostFile(file *multipart.File, header *multipart.FileHeader) error {
dstPath := filepath.Join("web/static/img/posts", header.Filename)
dst, err := os.Create(dstPath)
if err != nil {
log.Printf("os.Create: %v", err)
return err
}
defer dst.Close()
if _, err := io.Copy(dst, *file); err != nil {
log.Printf("io.Copy: %v", err)
return err
}
return nil
}
func main() {
// -----------------
// SETUP
@@ -119,37 +141,27 @@ func main() {
r.Post("/{slug}/threads", func(w http.ResponseWriter, r *http.Request) {
slug := chi.URLParam(r, "slug")
subject := r.FormValue("subject")
body := r.FormValue("body")
// 10 MB memory limit
if err := r.ParseMultipartForm(10 << 20); err != nil {
http.Error(w, "Bad form data", http.StatusBadRequest)
log.Printf("ParseForm: %v", err)
if err := r.ParseMultipartForm(FILE_MEM_LIMIT); err != nil {
http.Error(w, "Failed to parse form", http.StatusBadRequest)
log.Printf("ParseMultipartForm: %v", err)
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Failed to retrieve file from form", http.StatusBadRequest)
http.Error(w, "Failed to retrive file from form", http.StatusBadRequest)
log.Printf("FormFile: %v", err)
return
}
defer file.Close()
subject := r.FormValue("subject")
body := r.FormValue("body")
dstPath := filepath.Join("web/static/img/posts", header.Filename)
dst, err := os.Create(dstPath)
if err != nil {
http.Error(w, "Failed to create file", http.StatusInternalServerError)
log.Printf("os.Create: %v", err)
return
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
if err := savePostFile(&file, header); err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
log.Printf("io.Copy: %v", err)
log.Printf("savePostFile: %v", err)
return
}
@@ -172,8 +184,33 @@ func main() {
}
body := r.FormValue("body")
mediaPath := ""
if err := database.PutPost(db, threadId, body); err != nil {
// 10 MB memory limit
if err := r.ParseMultipartForm(FILE_MEM_LIMIT); err != nil {
http.Error(w, "Failed to parse form", http.StatusBadRequest)
log.Printf("ParseMultipartForm: %v", err)
return
}
file, header, err := r.FormFile("file")
if err != nil {
if !errors.Is(err, http.ErrMissingFile) {
http.Error(w, "Failed to retrive file from form", http.StatusBadRequest)
log.Printf("FormFile: %v", err)
return
}
} else {
defer file.Close()
if err := savePostFile(&file, header); err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
log.Printf("savePostFile: %v", err)
return
}
mediaPath = header.Filename
}
if err := database.PutPost(db, threadId, body, mediaPath); err != nil {
http.Error(w, "Failed to create post", http.StatusInternalServerError)
log.Printf("PutPost: %v", err)
return
+11 -7
View File
@@ -2,16 +2,22 @@ package views
import (
"fmt"
database "github.com/dominicf2001/comfychan/internal/database"
"github.com/dominicf2001/comfychan/internal/database"
"github.com/dominicf2001/comfychan/web/views/shared"
)
templ NewThreadForm(board database.Board) {
<form hx-encoding="multipart/form-data" style="display: none;" id="newThreadForm" hx-swap="none" hx-post={
fmt.Sprintf("/%s/threads", board.Slug) } _="on htmx:afterRequest
<form
hx-encoding="multipart/form-data"
style="display: none;"
id="newThreadForm"
hx-swap="none"
hx-post={ fmt.Sprintf("/%s/threads", board.Slug) }
_="on htmx:afterRequest
hide me
then show #newThreadBtn
then trigger refreshThreads on body">
then trigger refreshThreads on body"
>
<table>
<tbody>
<tr class="new-post-form-field">
@@ -46,9 +52,7 @@ templ Board(board database.Board) {
@shared.Layout() {
@BoardHeader(board)
<div class="new-post-container">
<button _="on click
hide me
then show #newThreadForm" id="newThreadBtn">[New Thread]</button>
<button _="on click hide me then show #newThreadForm" id="newThreadBtn">[New Thread]</button>
@NewThreadForm(board)
</div>
<div hx-get={ fmt.Sprintf("/hx/%s/catalog", board.Slug) } hx-trigger="load, refreshThreads from:body"></div>
+22 -6
View File
@@ -10,15 +10,18 @@ import (
templ ThreadPosts(posts []database.Post) {
for _, post := range (posts) {
<article class="post">
if post.MediaPath != "" {
<div class="post-img-container">
<img src={ fmt.Sprintf("/static/img/posts/%s", post.MediaPath) } class="post-img"/>
</div>
}
<header class="post-header">
<span class="post-author">{ post.Author }</span>
<span class="post-date">{ post.CreatedAt.Format("01/02/2006") }</span>
<span class="post-time">{ post.CreatedAt.Format("15:04") }</span>
<span class="post-num">No. { strconv.Itoa(post.Id) }</span>
</header>
<section>
<p>{ post.Body }</p>
</section>
</article>
<br/>
}
@@ -28,15 +31,26 @@ templ Thread(board database.Board, thread database.Thread, posts []database.Post
@shared.Layout() {
@BoardHeader(board)
<div class="new-post-container">
<form id="newPostForm" hx-swap="none" hx-post={ fmt.Sprintf("/%s/threads/%d", board.Slug, thread.Id) } _="on htmx:afterRequest
<form
hx-encoding="multipart/form-data"
id="newPostForm"
hx-swap="none"
hx-post={ fmt.Sprintf("/%s/threads/%d",
board.Slug, thread.Id) }
_="on htmx:afterRequest
set #newPostBody.value to ''
then trigger refreshPosts on body">
then trigger refreshPosts on body"
>
<table>
<tbody>
<tr class="new-post-form-field">
<th>comment</th>
<td><textarea id="newPostBody" name="body" required></textarea></td>
</tr>
<tr class="new-post-form-field">
<th>File</th>
<td><input name="file" type="file"/></td>
</tr>
</tbody>
</table>
<button type="submit">Submit</button>
@@ -58,8 +72,10 @@ templ Thread(board database.Board, thread database.Thread, posts []database.Post
</header>
<p class="post-body">{ posts[0].Body }</p>
</article>
<div hx-get={ fmt.Sprintf("/hx/%s/threads/%d/posts", board.Slug, thread.Id) }
hx-trigger="load, refreshPosts from:body"></div>
<div
hx-get={ fmt.Sprintf("/hx/%s/threads/%d/posts", board.Slug, thread.Id) }
hx-trigger="load, refreshPosts from:body"
></div>
</div>
}
}