7. js / lib / muestraImagenSeleccionada.js

1
import { selectorDeNombre } from "./muestraObjeto.js"
2
3
/**
4
 * @param {HTMLInputElement} input
5
 * @param {HTMLInputElement} img
6
 */
7
export function muestraImagenSeleccionada(input, img) {
8
 return new Promise((resolve, reject) => {
9
  setTimeout(() => {
10
11
   try {
12
13
    const dataUrl = getDataUrlDeSeleccion(input)
14
15
    if (dataUrl === "") {
16
17
     const src = input.dataset.src
18
     if (src === undefined || src === "") {
19
      img.hidden = true
20
      img.src = ""
21
     } else {
22
      img.hidden = false
23
      img.src = src
24
     }
25
26
    } else {
27
28
     img.hidden = false
29
     img.src = dataUrl
30
31
    }
32
33
    resolve(true)
34
35
   } catch (error) {
36
37
    img.hidden = true
38
39
    reject(error)
40
41
   }
42
43
  },
44
   500)
45
 })
46
}
47
48
/**
49
 * @param {HTMLInputElement} input
50
 */
51
export function getDataUrlDeSeleccion(input) {
52
 const seleccion = getArchivoSeleccionado(input)
53
 if (seleccion === null) {
54
  return ""
55
 } else {
56
  return URL.createObjectURL(seleccion)
57
 }
58
}
59
60
61
/**
62
 * @param { HTMLInputElement } input
63
 */
64
export function getArchivoSeleccionado(input) {
65
 if (input.type !== "file") throw new Error('El input debe ser type="file')
66
 const seleccion = input.files
67
 if (seleccion === null) throw new Error('El input debe ser type="file')
68
 if (seleccion.length === 0) {
69
  return null
70
 } else {
71
  return seleccion.item(0)
72
 }
73
}
skip_previous skip_next