티스토리 뷰
728x90
반응형
php에서 dropzone을 이용하여 파일 업로드 하는 방법
Step 01 - html 선언
* dropzone의 class이름이 class="dropzone"으로 선언되어 있어야 한다.
1
2
3
4
5
6
7
8
9
10
|
<div class="row m-t-20">
<label class="col-sm-2 text-center f-s-20 m-t-5" for="dropzone">첩부파일</label>
<div class="col-sm-10 col-xs-12">
<div class="dropzone" id="fileDropzone">
<div class="dz-message needsclick">
여기에 파일을 끌어 놓거나 업로드하려면 클릭하십시오.
</div>
</div>
</div>
</div>
|
cs |
Step 02 - javascript 선언
* 선언한 class를 가지고 설정을 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<script type="text/javascript">
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
url: '/app/board/do_upload', // 파일 업로드할 url
method: "post",
paramName: 'upload',
params: {
md_id:"<?=$view->md_id?>",
target_type: "file",
timestamp:"<?=$view->timestamp?>"
},
addRemoveLinks: true,
dictRemoveFile: "삭제"
<?if(isset($view->files[0])):?>
// 초기 실행 시
, init: function() {
var thisDropzone = this;
<?foreach ($view->files as $item):?>
var mockFile = {
code: "<?=$item->code?>",
name: "<?=$item->orig_name?>",
path: "/files/board/<?=$view->md_id?>/<?=$item->raw_name . $item->file_ext?>",
size: "<?=$item->file_size?>"
};
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, mockFile.path);
thisDropzone.emit("complete", mockFile);
thisDropzone.files.push(mockFile);
<?endforeach;?>
}
<?endif;?>
,
removedfile: function(file) {
// 파일 삭제 시
var code = file.code == undefined ? file.temp.code : file.code; // 파일 업로드시 return 받은 code값
$.ajax({
type: 'POST',
url: '/app/board/do_delete', // 파일 삭제할 url
data: {code: code},
success: function(data) {
console.log('success: ' + data);
}
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
, success: function (file, response) {
// 파일 업로드 성공 시
file.temp = JSON.parse(response); // 파일을 삭제할 수도 있으므로 변수로 저장
console.log(file);
}
});
</script>
|
Step 03 - PHP에서 do_upload 함수 선언
* javascript에서 파라미터로 건네받은 것들을 선언한 뒤에 사용
$_FILES['upload'] 이라고 선언한 이유는 자바스크립트에서 paraName을 upload라고 지칭하였기 때문에 $_FILES['upload']로 선언
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
public function do_upload(){
if($_FILES['upload']['name'] != ""):
$md_id = $this->input->get_post('md_id', true);
$target_type = $this->input->get_post('target_type', true);
$timestamp = $this->input->get_post('timestamp', true);
$files = $_FILES;
$directory = "./files/board"; // 파일 저정 디렉토리
if(!is_dir($directory)){
mkdir($directory, 0707);
chmod($directory, 0707);
}
if(isset($_FILES['upload'])):
if($_FILES['upload']['name'] != ""):
$_FILES['upload']['name'] = $files['upload']['name'];
$_FILES['upload']['type'] = $files['upload']['type'];
$_FILES['upload']['tmp_name'] = $files['upload']['tmp_name'];
$_FILES['upload']['error'] = $files['upload']['error'];
$_FILES['upload']['size'] = $files['upload']['size'];
endif;
endif;
$config = array();
$config['encrypt_name'] = true;
$config['upload_path'] = $directory;
$config['allowed_types'] = '*';
$config['max_size'] = '1024000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('upload')){
$result = array(
"code"=>0,
"message"=>$this->upload->display_errors()
);
return $result;
exit;
}else{
$upload_data = $this->upload->data();
$file_data = array();
$file_data['md_type'] = 'board';
$file_data['md_id'] = $md_id;
$file_data['table'] = 'board';
$file_data['timestamp'] = $timestamp;
$file_data['target_type'] = $target_type;
$file_data['file_name'] = $upload_data['file_name'];
$file_data['file_type'] = $upload_data['file_type'];
$file_data['file_path'] = $upload_data['file_path'];
$file_data['full_path'] = $upload_data['full_path'];
$file_data['raw_name'] = $upload_data['raw_name'];
$file_data['orig_name'] = $upload_data['orig_name'];
$file_data['client_name'] = $upload_data['client_name'];
$file_data['file_ext'] = $upload_data['file_ext'];
$file_data['file_size'] = $upload_data['file_size'];
$file_data['is_image'] = $upload_data['is_image'];
$file_data['image_width'] = $upload_data['image_width'];
$file_data['image_height'] = $upload_data['image_height'];
$file_data['image_type'] = $upload_data['image_type'];
$file_data['image_size_str'] = $upload_data['image_size_str'];
$file_result = $this->Common_file_model->write($file_data); //DB에 값 저장
if($file_result){
$fk_code = $this->db->insert_id();
echo json_encode(array("code"=>$fk_code,"object"=>$upload_data));
exit;
}else{
back("파일를 DB에 등록하지 못했습니다.");
exit;
}
}
endif;
}
|
cs |
Step 04 - 업로드한 파일 삭제 방법
* javascript에서 removedfile 이벤트는 파일을 삭제시켜줄 수 있는 이벤트이다.
ajax을 이용하여 php의 do_delete 함수에 내가 업로드한 파일의 code를 보내서 삭제를 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public function do_delete(){
$this->load->model('Common_file_model');
$data = array();
$data['view'] = $this->Common_file_model->view(array('code'=>$this->input->post('code', true)));
if(isset($data['view']->code)){
$this->db->trans_start();
$this->common_file->delete(array('code' => $data['view']->code)); //DB 삭제
$result = $this->db->trans_complete();
if($result):
//서버단에서도 파일 삭제
if(is_file($data['view']->file_path.$data['view']->raw_name.$data['view']->file_ext)):
@unlink($data['view']->file_path.$data['view']->raw_name.$data['view']->file_ext);
endif;
echo "true";
exit;
else:
echo "false";
exit;
endif;
}else{
echo "false";
exit;
}
}
|
cs |
*참고
Dropzone의 init 이벤트를 이용하여 업로드한 첨부파일 가져오기

1. php의 컨트롤단에서 자신이 업로드한 file들을 select 절로 데이터를 가져온다
- 나는 컨트롤단에서 view라는 array에 files라는 이름으로 담아서 javascript단에서 사용하고 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
init: function() {
var thisDropzone = this;
<?foreach ($view->files as $item):?>
var mockFile = {
code: "<?=$item->code?>", // 파일의 code
name: "<?=$item->orig_name?>", // 파일의 이름
path: "/files/board/<?=$view->md_id?>/<?=$item->raw_name . $item->file_ext?>", // 파일의 경로
size: "<?=$item->file_size?>" // 파일의 size
};
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, mockFile.path);
thisDropzone.emit("complete", mockFile);
thisDropzone.files.push(mockFile);
<?endforeach;?>
}
|
cs |
728x90
반응형
'PHP > Codeigniter' 카테고리의 다른 글
PHP - Paging (0) | 2021.01.28 |
---|---|
php - nodejs을 이용한 채팅기능 구현 (5) 전체적인 소스 (0) | 2021.01.28 |
php - nodejs을 이용한 채팅기능 구현 (4) (0) | 2021.01.28 |
php - nodejs을 이용한 채팅기능 구현 (3) (0) | 2021.01.28 |
php - nodejs을 이용한 채팅기능 구현 (2) (0) | 2021.01.28 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- spring boot excel download oom
- redis sorted set
- spring boot redisson 분산락 구현
- polling publisher spring boot
- pipe and filter architecture
- spring boot redisson destributed lock
- spring boot 엑셀 다운로드
- redis 대기열 구현
- transactional outbox pattern
- spring boot redis 대기열 구현
- transactional outbox pattern spring boot
- spring boot redisson sorted set
- 레이어드 아키텍처란
- 트랜잭셔널 아웃박스 패턴 스프링부트
- 람다 표현식
- JDK Dynamic Proxy와 CGLIB의 차이
- spring boot excel download paging
- java userThread와 DaemonThread
- redis sorted set으로 대기열 구현
- pipeline architecture
- 트랜잭셔널 아웃박스 패턴 스프링 부트 예제
- microkernel architecture
- space based architecture
- java ThreadLocal
- 공간 기반 아키텍처
- service based architecture
- 자바 백엔드 개발자 추천 도서
- spring boot poi excel download
- @ControllerAdvice
- 서비스 기반 아키텍처
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함