본문 바로가기

WordPress/AJAX Upload

PHP AJAX Upload example

워드프레스 기반에서 AJAX를 이용하여 파일을 업로드하는 예



개요

워드프레스 기반이라는 제목을 사용하기는 했지만 여기서는 워드프레스 플러그인을 만드는 과정이 아니기 때문에 워드프레스와 관련한 부분은 거의 없다고 할 수 있다. 그냥에서 AJAX를 이용하여 파일을 업로드하고 서버측 PHP에서 파일을 수신하는 내용이라고 보는 것이 내용상 더 어울릴 것이다.

여기서는 우선 워드프레스 플러그인을 작성하기 위한 전 과정으로 AJAX와 PHP를 연동하여 파일을 업로드하는 기능을 알아보고자 한다

주의할 점은, 워드프레스에서 제공하는 템플릿 페이지에서는 이미 jQuery를 포함하고 있기 때문에 별도로 jQuery라이브러리를 포함해서는 안된다. 또 한가지는 jQuery함수 오브젝트를 표현할 때 사용하는 '$' 기호 대신에 'jQuery' 라는 이름을 사용해야 한다. '$' 기호는 PHP언어에서도 변수를 표현할 때 사용하기 때문이다



테스트 환경

Autoset 9

WordPress 4.4



클라이언트 측 코드

워드프레스에서 생성해준 템플릿 페이지를 편집하여 클라이언트 코드를 아래처럼 작성한다.

업로드 폼에 입력된 텍스트와 파일을 jQuery.ajax() 함수를 이용하여 서버에 전송하는 예이다

<script>
  console.log('javascript started');
  jQuery(function(){
    console.log('jQuery ready!');
    jQuery('#upload').on('click', function(){
      console.log('button clicked!');
      var data = new FormData();
      data.append('desc',jQuery('#desc').val());
      data.append('file1', jQuery('#file1').prop('files')[0]);
      jQuery.ajax({
        url: '../ajax-upload.php',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(res)
        {
            console.log('응답수신:'+res.result);
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            console.log('서버오류: ' + textStatus);
        }
    }); //end of ajax()
    }); // end of click handler
  }); // end of ready();
</script>
<form id="upload-form">
   파일에 대한 설명 <input type="text" name="desc" id="desc" value="AJAX Upload Test"><br>
   <input type="file" name="file1" id="file1"><br>
   <button id="upload" type="button">Upload</button>
</form>



서버측 PHP ( 워드프레스 루트 폴더/ajax-upload.php )

위의 업로드폼에서 아래의 서버측 스크립트에 직접 접근하도록 ajax()함수의 url을 설정했기 때문에 아래의 파일은 서버측의 워드프레스 루트 폴더에 저장해야 한다

<?php
log_d('ajax-upload.php','요청 전달됨');
log_d('desc', $_POST['desc']);

if ( 0 < $_FILES['file1']['error'] ) {
	header( "Content-Type: application/json" );
	echo "{\"result\": false}";
}
else {
	$desc = $_POST['desc'];
	$fname = iconv('UTF-8', 'EUC-KR', $_FILES['file1']['name']);
	$moved = move_uploaded_file($_FILES['file1']['tmp_name'], 'C:test/uploads/' .$fname);
	header( "Content-Type: application/json" );
	echo "{\"result\":$moved}";
}

function log_d($tag, $msg) {
	$file = fopen('my-debug.log','a');
	fwrite($file, $tag.':'.$msg."\r\n");
	fclose($file);
}
?>