ProcessWire图像上传的两种实现方法

一 Ajax异步实现图像上传

前端HTML表单

<form class="forum-form" method="post" action="/path/to/page/" enctype="multipart/form-data" accept-charset="utf-8">
	<input type="hidden" name="avatar_update" value="1" class="hidden">
    	<input type="file" multiple="multiple" id="inputfile" class="inputfile file" name="avatarimg[]">        
    <button class="btn-avatar-submit button" type="submit">提交</button>
</form>

前端JS

$(document).on("click",".btn-avatar-submit",function(){

	var $files = new Array();
	$('input[name="avatarimg[]"]').each(function() {
		if(this.value.length>0)
		{
	   	   $files.push(this.value);
		}
	});	
	if($files.length>0)
	{
		  var data = new FormData();
		  data.append('avatar_update',1);
		  $.each($('#inputfile')[0].files, function(i, file) {
			  data.append('upload_file'+i, file);
		  });
		  $.ajax({
			  url:$baseurl+'home/setting/',
			  type:'POST',
			  data:data,
			  cache: false,
			  contentType: false,		//important
			  processData: false,		//important
			  dataType: "json",
			  beforeSend: function(){
				  pagePosting();
				  },
			  success:function(data){
				  if(data.msg==1)
				  {
					  msgShow("success","头像保存完毕!","","",1000);
					  $(".avatar").find('img').attr("src",data.img);
				  }
				  else if(data.msg==2)
				  {
					  msgShow("error","没有任何文件!","","",1000);
				  }
			  },
			  error:function(){
				  msgShow("error","上传错误!","","",1000);
			  }
		  });
	}
	else
	{
		msgShow("alert","请选择一个图片文件后再上传!",'','',2000);
		return false;
	}
	return false;

});

服务端

//upload user avatar
if($input->post->avatar_update==1)
{
	try{
		//$data['msg']=count($user->avatar);		
		if(count($user->avatar)>0)
		{
			$user->of(false); // turn off output formatting
			$user->avatar->deleteAll(); // ...or this line (choose one)
			$user->save('avatar'); // or use $page->save(); if also saving other changes											
			$user->of(true);
		}
		//upload image for user avatar	:  if there are array you can use for each
		if(count($_FILES)>0)
		{
			$keyarr=array_keys($_FILES);
			foreach($keyarr as $keyname)
			{
				$user->of(false);
				// instantiate the class and give it the name of the HTML field
				$u = new WireUpload($keyname);	//$_FILES  array name
				// tell it to only accept 1 file
				$u->setMaxFiles(1);
				// tell it to rename rather than overwrite existing files
				$u->setOverwrite(false);
				// have it put the files in their final destination. this should be okay since
				// the WireUpload class will only create PW compatible filenames
				$u->setDestinationPath($user->avatar->path());
				// tell it what extensions to expect
				$u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png'));
				// execute() returns an array, so we'll foreach() it even though only 1 file
				foreach($u->execute() as $filename) { 
					$user->avatar->add($filename);		
				}
				// save the page
				$user->save();
				$user->of(true);
			}
			$data['msg']=1;
			$data['img']=$user->avatar->first()->size(100,100)->url;
		}
		else
		{
			$data['msg']=3;
		}
		//end
		echo json_encode($data);
		die();					
	}catch (WireException $e) {
	  	// Print out message of exception : $e->getMessage()
		$data['msg']= $e->getMessage();
		echo json_encode($data);
		die();	
	}									
}

二 普通表单上传

前端html表单

<form class="forum-form" method="post" action="<?=$page->url?>"  enctype=multipart/form-data accept-charset="utf-8">
	<input type="hidden" name="avatar_update" value="1" />
    <input type="file" name="myavatar[]" accept="image/jpg,image/jpeg,image/gif,image/png" /> 
    <input type="file" name="myavatar[]" multiple="multiple" accept="image/jpg,image/jpeg,image/gif,image/png" />
    <button class="btn-avatar-submit" type="submit">提交</button>
</form>

后端处理

//upload user avatar
if($input->post->avatar_update==1)
{
	try{
		/*
		  if(count($user->avatar)>0)
		  {
			  $user->of(false); // turn off output formatting
			  $user->avatar->deleteAll(); // ...or this line (choose one)
			  $user->save('avatar'); // or use $page->save(); if also saving other changes											
			  $user->of(true);
		  }				
		  */
		  $user->of(false);
		  // instantiate the class and give it the name of the HTML field
		  $u = new WireUpload("myavatar");
		  // tell it to only accept 1 file
		  $u->setMaxFiles(3);
		  // max file size allow
		  $u->setMaxFileSize(1*1024*1024);
		  // tell it to rename rather than overwrite existing files
		  $u->setOverwrite(false);
		  // have it put the files in their final destination. this should be okay since
		  // the WireUpload class will only create PW compatible filenames
		  $u->setDestinationPath($user->avatar->path());
		  // tell it what extensions to expect
		  $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png'));
		  // execute() returns an array, so we'll foreach() it even though only 1 file
					//old
					/*
					foreach($u->execute() as $filename) { 
						$user->avatar->add($filename);		
					}
					// save the page
					$user->save();
					$user->of(true);
					*/
					//old end
					//update 0621
					$files = $u->execute();
					if($u->getErrors())
					{	 
						//foreach($files as $filename) @unlink($upload_path . $filename);
						foreach($u->getErrors() as $e) 	$data['msg'].=$e;
						echo json_encode($data);
						die();
					} else {
						foreach($u->execute() as $filename) 
						{ 
							$user->avatar->add($filename);		
						}
						// save the page
						$user->save();
						$user->of(true);
					}
					//update end	

	}catch (WireException $e) {
		// Print out message of exception : $e->getMessage()
		echo  $e->getMessage();
		die();	
	}		
				
}

Post Comment