Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Feature 이미지 크기 제한 및 최적화 #34

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions constants/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,17 @@ const MISSING_POST_FIELDS = {
MESSAGE: '포스트 내용이 없습니다.',
};

const FILE_TOO_LARGE = {
STATUS_CODE: 413,
MESSAGE: '1MB 이하의 이미지만 업로드 가능합니다.',
};

const UNSUPPORTED_FILE_TYPE = {
STATUS_CODE: 400,
MESSAGE:
'허용되지 않는 파일 형식입니다. JPG, JPEG, PNG 파일만 업로드 가능합니다.',
};

const MONGODB_URI_NOT_FOUND =
'Please define the MONGODB_URI environment variable inside .env';

Expand Down Expand Up @@ -120,4 +131,6 @@ export const ERRORS = {
UNKNOWN_ERROR,
LOGIN_REQUIRED,
MISSING_POST_FIELDS,
FILE_TOO_LARGE,
UNSUPPORTED_FILE_TYPE,
};
121 changes: 121 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"next-auth": "^4.23.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"sharp": "^0.32.6",
"react-router-dom": "^6.17.0",
"tailwindcss": "^3.3.3"
},
Expand Down
28 changes: 26 additions & 2 deletions src/app/api/v1/image/uploadFile/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { S3 } from '@aws-sdk/client-s3';
import createError from 'http-errors';
import { ERRORS } from 'constants/errors';
import { sendErrorResponse } from '@utils/response';
import sharp from 'sharp';

export const dynamic = 'force-dynamic';

Expand Down Expand Up @@ -72,19 +73,42 @@ async function POST(request) {
);
}

const allowedMimeTypes = ['image/jpeg', 'image/png'];

if (!allowedMimeTypes.includes(file.type)) {
throw createError(
ERRORS.UNSUPPORTED_FILE_TYPE.STATUS_CODE,
ERRORS.UNSUPPORTED_FILE_TYPE.MESSAGE,
);
}

const fileName = file.name;
const fileType = file.type;
const fileStream = file.stream();
let fileBuffer = Buffer.alloc(0);

const maxFileSize = 1 * 1024 * 1024;

for await (const chunk of fileStream) {
fileBuffer = Buffer.concat([fileBuffer, chunk]);

if (fileBuffer.length > maxFileSize) {
throw createError(
ERRORS.FILE_TOO_LARGE.STATUS_CODE,
ERRORS.FILE_TOO_LARGE.MESSAGE,
);
}
}

const optimizedBuffer = await sharp(fileBuffer)
.resize({ width: 500 })
.jpeg({ quality: 80 })
.toBuffer();

const s3Params = {
Bucket: bucketName,
Key: fileName,
Body: fileBuffer,
Body: optimizedBuffer,
ContentType: fileType,
ACL: 'public-read',
};
Expand All @@ -98,7 +122,7 @@ async function POST(request) {
file: {
url: fileUrl,
name: fileName,
size: fileBuffer.length,
size: optimizedBuffer.length,
},
});
} catch (error) {
Expand Down
22 changes: 20 additions & 2 deletions src/components/Editor.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import React, { useEffect, useRef } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import axios from 'axios';
import EditorJS from '@editorjs/editorjs';
Expand All @@ -10,6 +10,15 @@ import { ERRORS } from 'constants/errors';
function Editor({ author, postId, title, content, error, setError, isModify }) {
const ref = useRef(null);
const router = useRouter();
const [uploadError, setUploadError] = useState('');
const [showUploadError, setShowUploadError] = useState(false);

useEffect(() => {
if (showUploadError) {
const timer = setTimeout(() => setShowUploadError(false), 3000);
return () => clearTimeout(timer);
}
}, [showUploadError]);

useEffect(() => {
const initEditor = async () => {
Expand All @@ -29,8 +38,12 @@ function Editor({ author, postId, title, content, error, setError, isModify }) {
endpoints: {
byFile: `/api/v1/image/uploadFile`,
},
types: 'image/*',
types: 'image/jpeg, image/png',
captionPlaceholder: 'Enter caption',
onImageUploadError: (error) => {
setUploadError('1MB 이하의 이미지만 업로드 가능합니다.');
setShowUploadError(true);
},
},
},
},
Expand Down Expand Up @@ -76,6 +89,11 @@ function Editor({ author, postId, title, content, error, setError, isModify }) {

return (
<>
{showUploadError && (
<div className='fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-red-500 text-red px-4 py-2 rounded-md text-sm z-50'>
{uploadError}
</div>
)}
<div className='border-2 border-gray-300 rounded-lg mb-6'>
<div className='mt-2 ml-6'>
<div id='editorjs' />
Expand Down
21 changes: 13 additions & 8 deletions src/components/Profile/ProfileImageUploader.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
'use client';

import { useRef } from 'react';
import { useImageUpload } from '@utils/useImageUpload';
import Image from 'next/legacy/image';

function ProfileImageUploader({
uploadedImage,
userProfile,
handleImageUpload,
inputRef,
}) {
function ProfileImageUploader({ userProfile }) {
const inputRef = useRef();
const { uploadedImage, handleImageUpload, errorMessage } = useImageUpload(
userProfile.id,
);

return (
<div className='mb-10 flex flex-col items-center mb-5'>
<input
type='file'
accept='image/*'
accept='image/jpeg, image/png'
style={{ display: 'none' }}
ref={inputRef}
onChange={handleImageUpload}
onChange={(e) => {
handleImageUpload(e).catch(console.error);
}}
/>
<div className='rounded-full bg-white p-3 shadow-[0_0_10px_5px rgba(0, 0, 0, 0.3)]'>
<div className='rounded-full bg-white w-60 h-60 flex flex-col items-center justify-center relative overflow-hidden border-2 border-white'>
Expand All @@ -37,6 +41,7 @@ function ProfileImageUploader({
>
사진 업로드/변경
</button>
{errorMessage && <p className='text-red-600 my-2'>{errorMessage}</p>}
</div>
);
}
Expand Down
27 changes: 17 additions & 10 deletions utils/useImageUpload.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,42 @@
import { useState } from 'react';
import axios from 'axios';
import { ERRORS } from 'constants/errors';

export const useImageUpload = (userId) => {
const [uploadedImage, setUploadedImage] = useState(null);
const [errorMessage, setErrorMessage] = useState('');

const handleImageUpload = async (e) => {
const file = e.target.files[0];

if (!file) return;

const maxFileSize = 1 * 1024 * 1024;

if (file.size > maxFileSize) {
setErrorMessage(ERRORS.FILE_TOO_LARGE.MESSAGE);
return;
}

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

try {
const response = await axios.post('/api/v1/image/uploadFile', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});

if (response.data && response.data.file) {
const imageUrl = response.data.file.url;

const updateResponse = await axios.put(
`/api/v1/profile/updateImage/${userId}`,
{ imageUrl },
);
if (updateResponse.data && updateResponse.data.status === 200) {
setUploadedImage(imageUrl);
}
setUploadedImage(imageUrl);
setErrorMessage('');
}
} catch (error) {
error;
setErrorMessage(
error?.response?.data?.message || '업로드에 실패했습니다.',
);
}
};

return { uploadedImage, handleImageUpload };
return { uploadedImage, handleImageUpload, errorMessage };
};