Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 37 additions & 44 deletions nextstep-frontend/src/pages/NewPost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,17 @@ import { getUserAuth } from '../handlers/userAuth.ts';
const NewPost: React.FC = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [images, setImages] = useState<File[]>([]); // Store images locally
const navigate = useNavigate();
const auth = getUserAuth();

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();

try {
// Upload images to the server
const uploadedImages: { [placeholder: string]: string } = {};
for (const image of images) {
const formData = new FormData();
formData.append('file', image);

const response = await api.post(`/resource/image`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${auth.accessToken}`,
},
});

// Map the placeholder to the actual URL
const imageUrl = `${config.app.backend_url()}/resources/images/${response.data}`;
uploadedImages[image.name] = imageUrl;
}

// Replace placeholders in the content with actual URLs
let updatedContent = content;
Object.keys(uploadedImages).forEach((placeholder) => {
updatedContent = updatedContent.replace(placeholder, uploadedImages[placeholder]);
});

// Submit the post with the updated content
// Submit the post with the content (images are already uploaded and URLs are in place)
await api.post(`/post`, {
title,
content: updatedContent,
content,
});

navigate('/feed'); // Redirect to feed after successful post creation
Expand Down Expand Up @@ -87,29 +62,47 @@ const NewPost: React.FC = () => {
"paragraphFormat",
"alert",
],
imageUploadRemoteUrls: true,
imageUploadURL: `${config.app.backend_url()}/resource/image`,
imageUploadParams: {
Authorization: `Bearer ${auth.accessToken}`
},
imageUploadMethod: 'POST',
imageMaxSize: 5 * 1024 * 1024, // 5MB
imageAllowedTypes: ['jpeg', 'jpg', 'png', 'gif'],
events: {
// Custom image upload handling
"image.beforeUpload": async function (fileList: File[]) {
'image.beforeUpload': function (files: File[]) {
const editor = this as any;
const firstFile = fileList[0];

if (firstFile) {
// Generate a placeholder for the image
const placeholder = `[[image-${firstFile.name}]]`;
const file = files[0];
// Create FormData
const formData = new FormData();
formData.append('file', file);

// Insert the placeholder into the editor
editor.image.insert(placeholder, null, null, editor.image.get());
// Upload the image
fetch(`${config.app.backend_url()}/resource/image`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${auth.accessToken}`
},
body: formData
})
.then(response => response.text())
.then(imageId => {
// Construct the full image URL
const imageUrl = `${config.app.backend_url()}/resource/image/${imageId}`;
// Insert the uploaded image
editor.image.insert(imageUrl, null, null, editor.image.get());
})
.catch(error => {
console.error('Error uploading image:', error);
});

// Store the image locally
setImages((prevImages) => [...prevImages, firstFile]);
}

return false; // Prevent Froala's default upload mechanism
return false; // Prevent default upload
},
},
pluginsEnabled: ["image"], // Ensure image plugin is enabled
'image.error': function (error: any, response: any) {
console.error('Image upload error:', error, response);
}
}
}}
/>
<Button type="submit" fullWidth variant="contained" color="primary" sx={{ mt: 3, mb: 2 }}>
Expand Down
92 changes: 50 additions & 42 deletions nextstep-frontend/src/pages/PostDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -286,30 +286,34 @@ const PostDetails: React.FC = () => {
setEditedContent(editor.html.get());
}
},
"image.beforeUpload": async function (fileList: File[]) {
"image.beforeUpload": function (files: File[]) {
const editor = this as any;
const firstFile = fileList[0];

if (firstFile) {
const formData = new FormData();
formData.append("file", firstFile);

try {
const response = await api.post(`/resource/image`, formData, {
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${auth.accessToken}`,
},
});
const file = files[0];

// Create FormData
const formData = new FormData();
formData.append('file', file);

const imageUrl = `${config.app.backend_url()}/resources/images/${response.data}`;
editor.image.insert(imageUrl, null, null, editor.image.get());
} catch (error) {
console.error("Error uploading image:", error);
}
}
// Upload the image
fetch(`${config.app.backend_url()}/resource/image`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${auth.accessToken}`
},
body: formData
})
.then(response => response.text())
.then(imageId => {
// Construct the full image URL
const imageUrl = `${config.app.backend_url()}/resource/image/${imageId}`;
// Insert the uploaded image
editor.image.insert(imageUrl, null, null, editor.image.get());
})
.catch(error => {
console.error('Error uploading image:', error);
});

return false; // Prevent Froala's default upload mechanism
return false; // Prevent default upload
}
},
pluginsEnabled: ["image", "link", "paragraphFormat"],
Expand Down Expand Up @@ -405,30 +409,34 @@ const PostDetails: React.FC = () => {
setNewComment(editor.html.get());
}
},
"image.beforeUpload": async function (fileList: File[]) {
"image.beforeUpload": function (files: File[]) {
const editor = this as any;
const firstFile = fileList[0];
const file = files[0];

// Create FormData
const formData = new FormData();
formData.append('file', file);

if (firstFile) {
const formData = new FormData();
formData.append("file", firstFile);

try {
const response = await api.post(`/resource/image`, formData, {
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${auth.accessToken}`,
},
});

const imageUrl = `${config.app.backend_url()}/resources/images/${response.data}`;
editor.image.insert(imageUrl, null, null, editor.image.get());
} catch (error) {
console.error("Error uploading image:", error);
}
}
// Upload the image
fetch(`${config.app.backend_url()}/resource/image`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${auth.accessToken}`
},
body: formData
})
.then(response => response.text())
.then(imageId => {
// Construct the full image URL
const imageUrl = `${config.app.backend_url()}/resource/image/${imageId}`;
// Insert the uploaded image
editor.image.insert(imageUrl, null, null, editor.image.get());
})
.catch(error => {
console.error('Error uploading image:', error);
});

return false; // Prevent Froala's default upload mechanism
return false; // Prevent default upload
}
},
pluginsEnabled: ["image", "link", "paragraphFormat"]
Expand Down
Loading