Nicer file input

This commit is contained in:
Andy Smith
2026-01-20 12:02:00 -06:00
committed by Stanko K.R.
parent d55aa25f9a
commit ba260db8a2
4 changed files with 70 additions and 28 deletions
@@ -1,14 +1,31 @@
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "image", "input" ]
static targets = [ "image", "input", "fileName", "placeholder" ]
previewImage() {
const file = this.inputTarget.files[0]
if (file) {
this.imageTarget.src = URL.createObjectURL(file)
if (this.#file) {
this.imageTarget.src = URL.createObjectURL(this.#file)
this.imageTarget.onload = () => URL.revokeObjectURL(this.imageTarget.src)
}
}
previewFileName() {
this.#file ? this.#showFileName() : this.#showPlaceholder()
}
#showFileName() {
this.fileNameTarget.innerHTML = this.#file.name
this.fileNameTarget.removeAttribute("hidden")
this.placeholderTarget.setAttribute("hidden", true)
}
#showPlaceholder() {
this.placeholderTarget.removeAttribute("hidden")
this.fileNameTarget.setAttribute("hidden", true)
}
get #file() {
return this.inputTarget.files[0]
}
}