Adjuntar fotos en los mensajes
Presentación
Firebase Auth
Cloud Firestore
Cloud Storage
Cloud Functions
Curso Firebase para Web se encuentra en desarrollo. Vuelve pronto para encontrar nuevas lecciones.
- Primero crearemos la acción
uploadMessageFile
en el módulomessages
. Es casi un clon de su versión pararooms
.
async uploadMessageFile({ rootGetters }, { roomID, file }) {
const timestamp = Date.now();
const userUID = rootGetters["user/getUserUid"];
const uploadPhoto = () => {
let fileName = `rooms/${roomID}/messages/${userUID}-${timestamp}.jpg`;
return storage.ref(fileName).put(file);
};
function getDownloadURL(ref) {
return ref.getDownloadURL();
}
try {
let upload = await uploadPhoto();
return await getDownloadURL(upload.ref);
} catch (error) {
throw Error(error.message);
}
},
-
No te olvides de añadir la propiedad
photo
a la accióncreateMessage
. -
Ahora debemos añadir el botón para enviar la imagen.
<div class="control">
<button
@click="$refs.file.click()"
:disabled="isLoading"
type="button"
class="button"
:class="{ 'is-loading': isLoading }"
>
🌄
</button>
<input
@change="onFileChange"
ref="file"
type="file"
class="inputfile"
style="display: none !important;"
/>
</div>
- Además hay que ajustar los métodos para poder subir las imágenes.
async createMessage() {
try {
if (this.photo) {
this.fileURL = await this.$store.dispatch(
"messages/uploadMessageFile",
{
roomID: this.id,
file: this.photo
}
);
}
...
this.message = this.photo = this.fileURL = "";
}
}
- Nos quedaría poder mostrar la imagen que va a ser subida al usuario/a, permitiendo eliminarla al hacer click.
<div
v-if="photo"
@click="photo = null"
class="photo-preview"
:style="{ 'background-image': `url(${messagePhoto})` }"
></div>
- Y por último mostrar la imagen en el chat.
<!-- Message has photo -->
<div
v-if="message.photo"
class="message__photo"
:style="{ 'background-image': `url(${message.photo})` }"
></div>
Código inicial
¿Tienes alguna pregunta sobre esta lección de Curso Firebase para Web?
Resuelve todas tus dudas sobre Firebase en la Comunidad de Escuela Vue: un lugar donde participar, aprender y ayudar. ¡Te esperamos!.
Tras el registro (si no lo has hecho ya) serás redirigido/a al canal adecuado en la Comunidad.