CodeIgniter3

26. [CodeIgniter3] Dropzone을 사용하여 끌어서 놓기 파일 업로드

drizzle0925 2022. 1. 11. 15:02
728x90

파일 업로드는 파일을 동적으로 관리하는 웹 애플리케이션에서 가장 많이 사용되는 기능입니다.

파일은 PHP를 사용하여 서버에 쉽게 업로드할 수 있습니다.

또한 PHP를 사용하여 한 번에 여러 파일을 업로드할 수 있습니다.

오늘은 그중에서도 Dropzone이라는 javascript 라이브러리를 이용하여 이미지를 끌어서 업로드하는 방법에 대해서 알아보겠습니다.

 

Dropzone 라이브러리는 아래 사이트에서 다운로드 가능합니다.

https://www.dropzone.dev/js/

 

Dropzone.js

Dropzone.js is an open source library that provides beautiful and easy to use drag'n'drop file uploads with image previews.

www.dropzone.dev

 

 

아래 태그를 나중에 View 파일에 넣어줍니다.

 

Database

아래 쿼리를 사용하여 테이블을 생성합니다.

CREATE TABLE `files` (
  `id` int NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `uploaded_on` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

 

Controller

application/controllers/Upload_File 파일을 만들고 아래 코드를 입력합니다.

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
class Upload_File extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

        // file 모델을 호출합니다.
        $this->load->model('file');
    }

    public function index()
    {
        $data = array();

        // 데이터베이스에서 파일 데이터 가져오기
        $data['files'] = $this->file->getRows();

        // view 파일에 데이터를 전달합니다.
        $this->load->view('image', $data);
    }

    public function dragDropUpload()
    {
        // 파일 업로드 구성
        $config['max_size'] = 1024;
        $config['upload_path'] = './upload/';
        $config['allowed_types'] = '*';

        // 업로드 라이브러리 로드 및 초기화
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        // 서버에 파일 업로드
        if($this->upload->do_upload('file'))
        {
            $fileData = $this->upload->data();
            $uploadData['file_name'] = $fileData['file_name'];
            $uploadData['uploaded_on'] = date("Y-m-d H:i:s");

            // 데이터베이스 파일 정보 삽입 =
            $insert = $this->file->insert($uploadData);
        }
    }
}
?>

 

Model

application/models/File.php 파일을 만들고 아래 코드를 입력합니다.

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class File extends CI_Model
{
    function __construct()
    {
        $this->tableName = 'files';
    }

    /**
     * 데이터베이스에서 파일 데이터 가져오기
     * @param id 지정된 경우 단일 레코드를 반환하고 그렇지 않으면 모든 레코드를 반환합니다.
     */
    public function getRows($id = '')
    {
        $this->db->select('id, file_name, uploaded_on');
        $this->db->from('files');
        if($id)
        {
            $this->db->where('id', $id);
            $query = $this->db->get();
            $result = $query->row_array();
        }
        else
        {
            $this->db->order_by('uploaded_on', 'desc');
            $query = $this->db->get();
            $result = $query->result_array();
        }

        return !empty($result) ? $result : false;
    }

    /**
     * 데이터베이스에 파일 데이터 삽입
     * @param array 테이블에 삽입하기 위한 데이터 배열
     */
    public function insert($data = array())
    {
        $insert = $this->db->insert('files', $data);
        return $insert ? true : false;
    }
}
?>

 

View

application/views/image.php 파일을 만들고 아래 코드를 입력합니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Codeigniter 다중 드래그 앤 드롭 이미지 업로드</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.css' type='text/css' rel='stylesheet'>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js' type='text/javascript'></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h2>PHP Dropzone 파일 업로드 예제</h2>
                <form action="<?php echo base_url('Upload_File/dragDropUpload/'); ?>" class="dropzone"></form>
            </div>
        </div>
        <div class="gallery">
            <div class="col-md-12">
                <h3>업로드된 파일:</h3>
                <?php 
                if(!empty($files))
                {
                    foreach($files as $row)
                    {
                        $filePath = "./upload/".$row["file_name"];
                        $fileMime = mime_content_type($filePath);
                        ?>
                        <embed src="<?php echo base_url('upload/'.$row['file_name']); ?>" type="<?php echo $fileMime; ?>" width="200px" height="140px">
                        <?php
                    }
                }
                else
                {
                    echo '<p>No file(s) found...</p>';
                }
                ?>
            </div>
        </div>
    </div>
</body>
</html>

 

아래 URL로 접속합니다.

http://localhost/Upload_file/

 

 

파일을 업로드합니다.

 

파일이 정상적으로 업로드 되었습니다.

 

페이지를 새로고침 해봅니다.

업로드된 파일이 아래 표시됩니다.

 

Github : https://github.com/jun0925/codeigniter3-tutorials/commit/626e628becd92658fe85de8a28b56248b0dbb5fd

728x90