G. libclienteweb / muestraImagenSeleccionada.js

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