본문 바로가기

WordPress/AJAX Upload Plugin

WordPress, AJAX Upload Plugin example

워드프레스에 AJAX 업로드 플러그인 만들기 예



개요

워드프레스에서는 페이지 템플릿에 업로드 폼을 만들고 그 폼에 입력된 데이터와 파일을 AJAX를 이용하여 서버측으로 업로드하면 서버측에 미리 준비된 wp-admin/admin-ajax.php 에서 요청을 받고 요청에 포함된 'action' 파라미터의 값을 참조하여 do_action('wp_ajax_[액션 파라미터의 값]') 형식의 액션 후크를 생성하여 액션함수를 자동으로 호출하게 된다. 그러므로 서버측에서 파일 업로드 기능을 수행하는 액션함수가 실행되기 위해서는 add_action('wp_ajax_[액션 파라미터의 값]', '액션함수의 이름'); 부분이 반드시 필요하고 액션함수도 선언해야 한다.

서버측 PHP(액션함수)에서는 AJAX요청에 대한 응답으로 JSON 형태의 문자열을 전달하는 예이다



테스트 환경

Autoset 9

WordPress 4.4



wp-content/plugins/my-ajax-plugin-test/kcw-ajax-upload-plugin.php

<?php
/*
Plugin Name: My AJAX Upload Plugin
Plugin URI: http://micropilot.tistory.com
Description: 파일업로드 폼과 서버측 업로드 스크립트로 구성됨. 폼은 [my-ajax-fileupload-form]으로 포함가능
Version: 1.0
Author: Kim Chang Woon
Author URI: http://micropilot.tistory.com
*/
// wp_create_nonce(), wp_verify_nonce()함수를 찾지 못하는 경우 아래의 행이 반드시 필요함
require_once(ABSPATH .'wp-includes/pluggable.php'); 
 
// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
  
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array(
 // URL to wp-admin/admin-ajax.php to process the request
 'ajaxurl' => admin_url( 'admin-ajax.php' ),
  
 // generate a nonce with a unique ID "myajax-post-comment-nonce"
 // so that you can check it later when an AJAX request is sent
 'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
 )
);

add_shortcode('my-ajax-fileupload-form', 'show_ajax_upload_form');

function show_ajax_upload_form($atts){
?>
<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]);
	  data.append('action', 'kcw-upload-form'),
      jQuery.ajax({
        url: MyAjax.ajaxurl,
        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);
			alert(res.result?'파일업로드 성공':'업로드 실패');
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            console.log('서버오류: ' + textStatus);
			alert('서버오류:'+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
}

add_action('wp_ajax_kcw-upload-form', 'kcw_process_uploadform');

function kcw_process_uploadform(){

	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}";
	}
	exit;
}

?>

위의 예제에서 파일이 저장되는 서버상의 디렉토리는 cafe24.com 호스팅 서비스를 이용하는 경우에는 다음과 같이 할 수 있다

/home/hosting_users/[호스팅아이디]/www/ap_uploads/  <-- ap_uploads 디렉토리를 생성해주어야 한다