>  기사  >  백엔드 개발  >  PHP 양식 파일 iframe 비동기 업로드 튜토리얼 설명

PHP 양식 파일 iframe 비동기 업로드 튜토리얼 설명

巴扎黑
巴扎黑원래의
2017-09-08 15:02:181365검색

이 기사에서는 주로 PHP 양식 파일 iframe의 비동기 업로드 예를 자세히 소개하며, 관심 있는 친구는 이를 참조할 수 있습니다.

이 기사의 예는 PHP 양식 파일의 비동기 업로드에 대한 구체적인 코드를 모든 사람과 공유합니다. iframe의 경우, 구체적인 내용은 다음과 같습니다.

1. iframe 요소를 양식에 배치합니다.
2. 파일 업로드 컨트롤의 내용이 변경되면 JS가 트리거되어 양식의 작업을 설정합니다. 파일 업로드를 처리하고 양식의 대상을 설정하는 img_upload_process.php 파일 iframe의 경우 파일 업로드를 위해 iframe이 서버에 제출되도록 합니다.
3 파일 업로드가 img_upload_process.php에서 성공적으로 처리된 후, 성공적으로 저장되면 양식의 숨겨진 필드로 반환됩니다.
4. 양식 제출 버튼을 클릭하면 JS는 양식 데이터를 수신하는 form_process.php 파일에 양식 작업을 설정하고 양식의 대상은 다음과 같이 설정됩니다. _본인.

양식: asyn_uplaod.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片异步上传</title>
</head>
<body>
<!-- application/x-www-form-urlencoded 缺省编码类型 -->
<!-- multipart/form-data 多媒体传输协议 ,方法必须是post 既可以发送文本数据,也支持二进制数据上载 -->
<form action="" method="post" enctype="multipart/form-data">
 用户名: <input type="text" name="username" /><br /> 
 上传头像: <input type="file" id="avator" name="avator" onchange="startUpload(this.form)" />

 <iframe frameborder=&#39;0&#39; width=&#39;0&#39; height=&#39;0&#39; name="uploadframe"></iframe> 
 <input type="hidden" id="save_path" name="save_path" />
 <span id="loading"></span> <br /> 
 <img     style="max-width:90%"PHP 양식 파일 iframe 비동기 업로드 튜토리얼 설명" > <br />
 <input type="submit" name="submitted" value="提交" onclick="formSubmit(this.form)" />

</form>

<script>

function startUpload(formObj){
  document.getElementById(&#39;loading&#39;).innerHTML = &#39;上传中...&#39;; 
  formObj.action = &#39;img_upload_process.php&#39;; 
  formObj.target = &#39;uploadframe&#39;; 
  formObj.submit(); 
}


function formSubmit(formObj) {
 formObj.action = &#39;form_process.php&#39;; 
 formObj.target = &#39;_self&#39;;

 //清空文件上传内容,防止重复提交
 var fileObj = document.getElementById(&#39;avator&#39;) ;

 // for IE, Opera, Safari, Chrome
 if (fileObj.outerHTML) {
  fileObj.outerHTML = fileObj.outerHTML;
 } else { // FF(包括3.5)
  fileObj.value = "";
 }

 formObj.submit(); 
}

</script>

</body>
</html>

파일 업로드 처리 중: img_upload_process.php


<?php
include &#39;Upload.class.php&#39;;

$file = $_FILES[&#39;avator&#39;];
$upload = new Upload();//上传工具类对象


if($save_path = $upload->up($file)){//上传成功
 echo <<<STR
 <script> 
  window.parent.document.getElementById(&#39;uploaded_img&#39;).src = "$save_path";
  window.parent.document.getElementById(&#39;loading&#39;).innerHTML = &#39;上传成功&#39;; 
  window.parent.document.getElementById(&#39;save_path&#39;).value = "$save_path"; 
 </script>
STR;

}else{
 $error = $upload->error();
 echo <<<STR
 <script>
  window.parent.document.getElementById(&#39;uploaded_img&#39;).src = "";
  window.parent.document.getElementById(&#39;loading&#39;).innerHTML = "上传失败: $error";
 </script>
STR;

}

파일 업로드 도구 클래스: Upload.class.php


<?php
class Upload{
 private $path; //文件上传目录
 private $max_size; //上传文件大小限制
 private $errno; //错误信息号
 private $mime = array(&#39;image/jpeg&#39;,&#39;image/png&#39;,&#39;image/gif&#39;);//允许上传的文件类型

 /**
  * 构造函数,
  * @access public
  * @param $path string 上传的路径
  */
 public function __construct($path = &#39;./&#39; ){
  $this->path = $path;
  $this->max_size = 1000000;
 }

 /**
  * 文件上传的方法,分目录存放文件
  * @access public
  * @param $file array 包含上传文件信息的数组
  * @return mixed 成功返回上传的文件名,失败返回false
  */
 public function up($file){
  //判断文件是否是通过 HTTP POST 上传,防止恶意欺骗
  /*
  if (! is_uploaded_file($file[&#39;tmp_name&#39;])) {
   $this->errno = 5; //设置错误信息号为5,表示非法上传
   return false;
  }
  */

  //判断是否从浏览器端成功上传到服务器端
  if ($file[&#39;error&#39;] == 0) {
   # 上传到临时文件夹成功,对临时文件进行处理
   //上传类型判断
   if (!in_array($file[&#39;type&#39;], $this->mime)) {
    # 类型不对
    $this->errno = -1; 
    return false;
   }

   //判断文件大小
   if ($file[&#39;size&#39;] > $this->max_size) {
    # 大小超出配置文件的中的上传限制
    $this->errno = -2;
    return false;
   }

   //获取存放上传文件的目录
   $sub_path = date(&#39;Ymd&#39;).&#39;/&#39;;
   if (!is_dir($this->path . $sub_path)) {
    # 不存在该目录,创建之
    mkdir($this->path . $sub_path);
   }

   //文件重命名,由当前日期 + 随机数 + 后缀名
   $file_name = date(&#39;YmdHis&#39;).uniqid().strrchr($file[&#39;name&#39;], &#39;.&#39;);

   //准备就绪了,开始上传
   if (move_uploaded_file($file[&#39;tmp_name&#39;], $this->path . $sub_path . $file_name)) {
    # 移动成功
    return $sub_path . $file_name;
   } else {
    # 移动失败
    $this->errno = -3;
    return false;
   }

  } else {
   # 上传到临时文件夹失败,根据其错误号设置错误号
   $this->errno = $file[&#39;error&#39;];
   return false;
  }

 }

 /**
  * 多文件上传方法
  * @access public
  * @param $file array 包含上传文件信息的数组,是一个二维数组
  * @return array 成功返回上传的文件名构成的数组, ?如果有失败的则不太好处理了
  */
 public function multiUp($files){
  //在多文件上传时,上传文件信息 又是一个多维数组,如$_FILES[&#39;userfile&#39;][&#39;name&#39;][0],$_FILES[&#39;userfile&#39;][&#39;name&#39;][1]
  //我们只需要遍历该数组,得到每个上传文件的信息,依次调用up方法即可
  foreach ($files[&#39;name&#39;] as $key => $value) {
   # code...
   $file[&#39;name&#39;] = $files[&#39;name&#39;][$key];
   $file[&#39;type&#39;] = $files[&#39;type&#39;][$key];
   $file[&#39;tmp_name&#39;] = $files[&#39;tmp_name&#39;][$key];
   $file[&#39;error&#39;] = $files[&#39;error&#39;][$key];
   $file[&#39;size&#39;] = $files[&#39;size&#39;][$key];
   //调用up方法,完成上传
   $filename[] = $this->up($file);
  }
  return $filename;
 }

 /**
  * 获取错误信息,根据错误号获取相应的错误提示
  * @access public
  * @return string 返回错误信息
  */
 public function error(){
  switch ($this->errno) {
   case -1:
    return &#39;请检查你的文件类型,目前支持的类型有&#39;.implode(&#39;,&#39;, $this->mime);
    break;
   case -2:
    return &#39;文件超出系统规定的大小,最大不能超过&#39;. $this->max_size;
    break;
   case -3:
    return &#39;文件移动失败&#39;;
    break;
   case 1:
    return &#39;上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值,其大小为&#39;.ini_get(&#39;upload_max_filesize&#39;);
    break;
   case 2:
    return &#39;上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值,其大小为&#39; . $_POST[&#39;MAX_FILE_SIZE&#39;];
    break;
   case 3:
    return &#39;文件只有部分被上传&#39;;
    break;
   case 4:
    return &#39;没有文件被上传&#39;;
    break;
   case 5:
    return &#39;非法上传&#39;;
    break;
   case 6:
    return &#39;找不到临时文件夹&#39;;
    break;
   case 7:
    return &#39;文件写入临时文件夹失败&#39;;
    break;
   default:
    return &#39;未知错误,灵异事件&#39;;
    break;
  }
 }
}

양식 제출 처리 중: form_process.php


<?php
var_dump($_REQUEST);
var_dump($_FILES);

양식 제출 버튼을 클릭하세요. 결과:

PHP 양식 파일 iframe 비동기 업로드 튜토리얼 설명

위 내용은 PHP 양식 파일 iframe 비동기 업로드 튜토리얼 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.