好库网 好库网首页 | 我的好库
好饱的专栏

PHP中利用jQuery实现SWF图像上传和裁剪

发布者:好饱
发布日期:2011/5/10 22:00:54   更新日期:2011/5/11 9:13:09
阅读次数:4199
评分:4.80
介绍:最近,我需要一个PHP使用SWF上传图像并进行裁剪的插件,但我没有找到,我试图结合 这些要求:SWF上传,裁剪,使用jQuery和PHP。
正文:

 

下载源代码

 

最近,我需要一个PHP使用SWF上传图像并进行裁剪的插件,但我没有找到,我试图结合

这些要求:SWF上传,裁剪,使用jQuery和PHP。

 

我找到了一些资料,关于SWF上传http://code.google.com/p/swfupload/

jQuery图像裁剪http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop/的内容,

另一个要求是限制上传一个文件,指定具体的图像类型和文件大小。 这些要求还需要一个PHP验证。

 

PHP中我们需要启用GD库。

 

好了,让我们看看如何实现吧:

 

1.添加jQuery和PHP裁剪过程所需的JS变量

 

<?php
require_once("config.php");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<meta name="generator" content="http://www.php-code.net" />
	<title>SWF image upload & crop for php using jQuery</title>
    <script type="text/javascript">
    //<![CDATA[
        var baseURL = "<?php echo BASE_URL;?>";
 
        var jsThumbWidth = "100"; 	//this is the thumb width after 
				//cropping the original image using jQuery
        var jsThumbHeight= "100"; 	//this is the thumb height after 
				//cropping the original image using jQuery
        var jsCurrentLargeImageWidth;
        var jsCurrentLargeImageHeight;
 
        var varX1= 0;
        var varY1= 0;
        var varX2= 0;
        var varY2= 0;
        var varW = 0;
        var varH = 0;
    //]]>
    </script>

config.php 文件包含配置设置,就像如下代码:

 

<?php
define("BASE_URL", "http://demo.php-code.net/swf_upload_and_crop");
?>

2. 包含所有必须的文件(JS和CSS):

 

<script type="text/javascript" src="<?php echo BASE_URL;?>
	/swf_upload_and_crop/js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL;?>
	/swf_upload_and_crop/js/functions.js"></script>
<script type="text/javascript" src="<?php echo BASE_URL;?>
	/swf_upload_and_crop/js/upload/jquery.imgareaselect.js">
	</script><!-- for jQuery cropping-->
<script type="text/javascript" src="<?php echo BASE_URL;?>
	/swf_upload_and_crop/js/upload/purejstemplate_jquery.js">
	</script> <!-- for loading display-->
<script type="text/javascript" src="<?php echo BASE_URL;?>
	/swf_upload_and_crop/js/upload/swfupload.js">
	</script><!-- for SWF upload-->
<script type="text/javascript" src="<?php echo BASE_URL;?>
	/swf_upload_and_crop/js/upload/swfupload.handlers.js">
	</script><!-- for SWF upload-->
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL;?>
	/swf_upload_and_crop/css/main.css" />
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL;?>
	/swf_upload_and_crop/css/upload/imgareaselect-default.css" />
	<!-- for jQuery cropping-->
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL;?>
	/swf_upload_and_crop/css/upload/swfupload.css" /><!-- for SWF upload-->

3. 为SWF上传设定配置

 

<script type="text/javascript">
        //<![CDATA[
        var swfu;
        window.onload = function() {
            var settings = {
                flash_url : baseURL + "/media/swfupload.swf",
                upload_url: baseURL + "/functions.php?upload_user_image",
                //post_params: {}, 	//if you need to send some parameters like, 
				//user id, PHP session id, etc
                file_size_limit : "1 MB", 	//the uploaded file cannot be 
					//bigger than this limit
                //debug: true, //if is set to true we can debug 
                prevent_swf_caching: true,
                file_types : "*.jpg; *.jpeg; *.gif; *.png",
                file_types_description: "Multimedia files",
                //file_upload_limit : 1,
                //file_queue_limit : 1,
                file_post_name : 'uploaded_image',
                custom_settings : {
                    messageTargetId : "message",
                    cancelButtonId : "btnCancel",
                    fileTemplateId : "tplFileQueue",
                    //Good
                    queueContainer : "uploadQueueContainer",
                    queue : {},
                        uploadSessionError : false
                },
                // Button settings
                button_width: "61",
                button_height: "22",
                button_placeholder_id: "spanButtonPlaceHolder",
                button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
                button_cursor: SWFUpload.CURSOR.HAND,
                // The event handler functions are defined in handlers.js
                swfupload_loaded_handler : swfUploadLoaded,
                file_queued_handler : fileQueued,
                file_queue_error_handler : fileQueueError,
                file_dialog_complete_handler : fileDialogComplete,
                upload_start_handler : uploadStart,
                upload_progress_handler : uploadProgress,
                upload_error_handler : uploadError,
                upload_success_handler : uploadSuccess,
                upload_complete_handler : uploadComplete
                //queue_complete_handler : queueComplete  // Queue plugin event
            };
            swfu = new SWFUpload(settings);
        };
        //]]>
    </script>
</head>

4. 创建SWF上传HTML模板

<body>
    <h2>SWF image upload & crop for php using jQuery</h2>
    <div id="tplFileQueue" style="display:none;">
        <li id="#?=data.id?#" class="uploadOpen fileQueueItem">
            <div class="items">
                <strong>#?=data.name?#</strong>
                <b>#?=data.size?#</b>
                <b>#?=data.type?#</b>
                <em id="message">#?=data.message?#</em>
                <span class="status" >#?=data.status?#</span>
            </div>
        </li>
    </div>
    <div class="pageUpload" id="content">
        <form action="#" id="uploadForm">
            <div class="boxGray">
                <div class="boxGrayMargin">
                    <div id="spanButtonPlaceHolder"></div>
                    <input id="btnUpload" onclick="alert('da'); return false;" 
			type="button" value="Browse..." style="width: 61px; 
			height: 22px; font-size: 8pt;"/>
                    <p>Allowed image size: 1 MB. </p>
                    <p>Allowed extensions: *.jpg; *.jpeg; *.gif; *.png.</p>	
                </div>
            </div>
            <div id="divLoadingContent"  style="background-color: #FFFF66; 
		border-top: solid 4px #FF9966; border-bottom: 
		solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; 
		display: none;">SWFUpload is loading. Please wait...</div>
            <div id="divLongLoading"  style="background-color: #FFFF66; 
		border-top: solid 4px #FF9966; border-bottom: 
		solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; 
		display: none;">SWFUpload loading failed. 
		Please check to see if you have Flash activated and a 
		valid version of Flash Player.</div>
            <div id="divAlternateContent" style="background-color: #FFFF66; 
		border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966;
		margin: 10px 25px; padding: 10px 15px; display: none;">
                Sorry. SWFUpload loading failed.  You must install or 
			upgrade your Flash Player.
                Please visit <a href="http://www.adobe.com/shockwave/
		download/download.cgi?P1_Prod_Version=ShockwaveFlash">
		Adobe website</a> to download Flash Player.
            </div>
            <ul id="uploadQueueContainer" class="upload"></ul>
            <div class="boxGraySimple" id="footerStatus">
		<div class="boxGraySimpleTop"><div> 
		</div></div><div class="boxGraySimpleMargin">
                <div class="message"></div>
                <div class="submit">
                    <p><span class="btn"><a href="javascript:;" 
			onclick="save_upload();return false;" id="add_file">
			SAVE</a></span></p>
                </div>
            </div><div class="boxGraySimpleBottom"><div> </div></div></div>
        </form>
        <div id="thumbnail"></div>
    </div>
    <script type="text/javascript">
    //<![CDATA[
        $(document).ready(function(){
            $('#thumbnail').imgAreaSelect({show: true,
                                            x1: varX1, 
                                            y1: varY1,
                                            x2: varX2,
                                            y2: varY2,
                                            onSelectChange: showPreview});
        });
     //]]>
    </script>
</body>
</html>

5. save_upload用于保存图片(位于js/upload/swfupload.handlers.js),如果一切正常应该是这样(if(fileContro == 1) 指示了允许上传多少文件):

 

function save_upload(){
	var uploadError = 0;
	stats 			= swfu.getStats();
 
	var cropDataString = '';
	cropDataString += '&x1=' + $('#x1').val();
	cropDataString += '&y1=' + $('#y1').val();
	cropDataString += '&x2=' + $('#x2').val();
	cropDataString += '&y2=' + $('#y2').val();
	cropDataString += '&w=' + $('#w').val();
	cropDataString += '&h=' + $('#h').val();
 
	if(fileContor == 1){
		$.ajax({
            type: "post",
			url: baseURL + "/functions.php?save_upload",
			data: "file_name=" + fileName + cropDataString,
			cache: false,
			success: function(msg){
				msgJSON = JSON.parse(msg);
				if(msgJSON && typeof(msgJSON.response) 
				!= 'undefined' && msgJSON.response != 'ok'){
					if(msgJSON.response == 'error'){
					alert("The file type is 
					not within the allowed ones!");
					}
					else if(msgJSON.response == 
					'error_save'){
					alert("Image could not be saved!");
					}
					else if(msgJSON.response == 
					'error_dates'){
					alert("2 - No file added!");
					}
 
					if(stats.files_queued==0 && 
						fileContor == 0){
						uploadError=3;
					}
 
					if(uploadError==3){
						alert('3 - No file added!');
					}
				}
				else if(msgJSON && typeof(msgJSON.response) 
				!= 'undefined' && msgJSON.response == 'ok'){
                    //here comes your code for saving, I just put a redirect
					location.href = baseURL + 
				"/upload_images/" + msgJSON.file_name;
				}
				fileContor--;
			}
		});
	}
	else{
		alert("1 - No file added!");
	}
}
我使用了老式的JavaScript函数alert(),我建议你使用更好的版本,名称为jAlert(),
你可以找到更多相关文档:http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/

评论 [发表评论]
账号 密码 还没帐号呢,现在注册一个?

免责声明:好库网所展示的信息由买卖双方自行提供,其真实性、准确性和合法性由信息发布人负责。好库网不提供任何保证,并不承担任何法律责任。