식

파일업로드시 이미지 파일 특정 크기로 미리 줄여서 업로드 하기

· 2024-07-31 (수) 16:51:41 · 1443

작업간에 필요하여 Chat Gpt 에게 물어보면서 구현한 테스트 코드 입니다.

 

html 스크립트 코드는 아래와 같이 진행하고

서버단에서 썸네일 과정이 없기 때문에 쾌적하게 이용 가능합니다.

여러 사이즈로 resize가 필요한 경우에는 코드는 수정 해주셔야 합니다.

 

upload.php 파일로 저장해 주는 로직 입니다.

 

따로 라이브러리 사용하지 않고 진행 가능합니다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Resize and Upload</title>
</head>
<body>
    <input type="file" id="fileInput" onchange="handleFileSelect(event)"/>
    <button id="uploadButton" onclick="uploadImage()">Upload</button>
    <img src="" id="pre_view" />
    <script>

        let resizedImage;

        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file && file.type.startsWith('image/')) { // Only process image files
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = new Image();
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        const MAX_WIDTH = 1000; // 원하는 최대 너비
                        const MAX_HEIGHT = 1000; // 원하는 최대 높이
                        let width = img.width;
                        let height = img.height;

                        // 비율에 맞게 크기 조정
                        if (width > height) {
                            if (width > MAX_WIDTH) {
                                height *= MAX_WIDTH / width;
                                width = MAX_WIDTH;
                            }
                        } else {
                            if (height > MAX_HEIGHT) {
                                width *= MAX_HEIGHT / height;
                                height = MAX_HEIGHT;
                            }
                        }

                        canvas.width = width;
                        canvas.height = height;
                        ctx.drawImage(img, 0, 0, width, height);
                        resizedImage = canvas.toDataURL(file.type, 0.9); // 품질 90%
                    };
                    img.src = e.target.result;
                    document.getElementById('pre_view').src=e.target.result;
                };
                reader.readAsDataURL(file);
            } else {
                console.error('Selected file is not an image.');
            }
        }

        function uploadImage() {
            if (resizedImage) {
                const formData = new FormData();
                formData.append('image', resizedImage);

                fetch('/upload.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => console.log('Success:', data))
                .catch(error => console.error('Error:', error));
            } else {
                console.log('No image selected or image not resized yet.');
            }
        }
    </script>
</body>
</html>

 

upload.php

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $uploadDir = 'uploads/;
    $response = ['status' => 'success'];

    if (isset($_POST['image'])) {
        $data = $_POST['image'];

        if (preg_match('/^data:image\/(\w+);base64,/', $data, $typeMatch)) {
            $data = substr($data, strpos($data, ',') + 1);
            $type = strtolower($typeMatch[1]); // jpg, png, gif 등

            if (!in_array($type, ['jpg', 'jpeg', 'gif', 'png'])) {
                $response['status'] = 'error';
                $response['message'] = 'Invalid image type';
                echo json_encode($response);
                exit;
            }

            $data = base64_decode($data);

            if ($data === false) {
                $response['status'] = 'error';
                $response['message'] = 'Base64 decode failed';
                echo json_encode($response);
                exit;
            }

            $filePath = $uploadDir . uniqid() . '.' . $type;
            if (file_put_contents($filePath, $data)) {
                $response['file'] = $filePath;
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Failed to save file';
            }
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Invalid data URI';
        }
    } else {
        $response['status'] = 'error';
        $response['message'] = 'No image data';
    }


    echo json_encode($response);
}else {
    // Handle invalid request methods
    $response = ['status' => 'error', 'message' => 'Invalid request method'];
    echo json_encode($response);
}
?>

 

댓글을 작성하시려면 로그인이 필요합니다.

개발자팁

5,404건

개발과 관련된 유용한 정보를 공유하세요. 질문은 QA에서 해주시기 바랍니다.

+
분류 제목 글쓴이 날짜 조회
기타 24-12-30 조회 2,019
MySQL 24-12-14 조회 1,862
기타 24-12-14 조회 2,032
JavaScript 24-12-13 조회 2,164
JavaScript 24-12-13 조회 1,671
PHP 24-12-13 조회 2,141
PHP 24-11-26 조회 4,574
기타 24-11-14 조회 2,492
기타 24-10-30 조회 2,759
PHP 24-10-11 조회 2,268
JavaScript 24-10-10 조회 1,336
JavaScript 24-09-26 조회 1,883
24-09-25 조회 2,506
JavaScript 24-09-07 조회 2,132
24-09-11 조회 1,571
24-09-19 조회 4,268
24-09-10 조회 4,355
24-08-19 조회 2,954
24-10-03 조회 1,825
24-08-07 조회 1,311
24-07-23 조회 2,000
24-07-08 조회 1,584
24-06-27 조회 1,490
PHP 24-08-23 조회 1,693
PHP 24-07-31 조회 1,444
OS 24-07-22 조회 2,417
기타 24-07-22 조회 1,278
기타 24-07-12 조회 1,489
기타 24-07-02 조회 1,705
기타 24-07-02 조회 1,168