|
| 1 | + import { showMessage } from './messages.js'; |
| 2 | + |
| 3 | +// Function to toggle the profile picture update form visibility |
| 4 | +export function toggleProfilePictureForm() { |
| 5 | + const imageUploadForm = document.getElementById('imageUploadForm'); |
| 6 | + if (imageUploadForm.style.display === 'none' || imageUploadForm.style.display === '') { |
| 7 | + imageUploadForm.style.display = 'flex'; |
| 8 | + imageUploadForm.style.flexDirection = 'column'; |
| 9 | + } else { |
| 10 | + imageUploadForm.style.display = 'none'; |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +// Function to handle the profile picture update process |
| 15 | +export function handleProfilePictureUpdate(userData) { |
| 16 | + document.getElementById('imageInput').addEventListener('change', (event) => { |
| 17 | + const fileInput = event.target; |
| 18 | + const fileNameDisplay = document.getElementById('fileName'); |
| 19 | + if (fileInput.files.length > 0) { |
| 20 | + fileNameDisplay.textContent = fileInput.files[0].name; |
| 21 | + } else { |
| 22 | + fileNameDisplay.textContent = 'No file chosen'; |
| 23 | + } |
| 24 | + }); |
| 25 | + |
| 26 | + document.getElementById('imageUploadForm').addEventListener('submit', (event) => { |
| 27 | + event.preventDefault(); |
| 28 | + const imageInput = document.getElementById('imageInput'); |
| 29 | + const file = imageInput.files[0]; |
| 30 | + if (!file) { |
| 31 | + console.error('No image selected'); |
| 32 | + showMessage('No image selected', '#ProfileModal', 'error'); |
| 33 | + return; |
| 34 | + } |
| 35 | + const formData = new FormData(); |
| 36 | + formData.append('avatar', file); |
| 37 | + |
| 38 | + fetch(`/user/${userData.id}/`, { |
| 39 | + method: 'PATCH', |
| 40 | + headers: { |
| 41 | + 'Authorization': `Bearer ${userData.token}` |
| 42 | + }, |
| 43 | + body: formData |
| 44 | + }) |
| 45 | + .then(response => { |
| 46 | + if (!response.ok) { |
| 47 | + throw new Error('Network response was not ok'); |
| 48 | + } |
| 49 | + return response.json(); |
| 50 | + }) |
| 51 | + .then(data => { |
| 52 | + console.log('Image uploaded successfully:', data); |
| 53 | + showMessage('Profile picture updated successfully', '#ProfileModal', 'accept'); |
| 54 | + document.getElementById('avatar').src = `${data.avatar}?t=${new Date().getTime()}`; |
| 55 | + document.getElementById('imageUploadForm').style.display = 'none'; |
| 56 | + document.getElementById('imageInput').value = ''; |
| 57 | + document.getElementById('fileName').textContent = 'No file chosen'; |
| 58 | + }) |
| 59 | + .catch(error => { |
| 60 | + console.error('Error uploading image:', error); |
| 61 | + showMessage('Error uploading image', '#ProfileModal', 'error'); |
| 62 | + document.getElementById('imageInput').value = ''; |
| 63 | + document.getElementById('fileName').textContent = 'No file chosen'; |
| 64 | + }); |
| 65 | + }); |
| 66 | +} |
0 commit comments