


A case study on how to asynchronously upload an iframe in a php form file
The example of this article shares the specific code for asynchronous upload of PHP form file iframe for your reference. The specific content is as follows
1. Place the iframe element in the form;
2. File upload When the content of the control changes, trigger JS to set the action of the form to the img_upload_process.php file that processes file uploads, and set the target of the form to iframe, so that the iframe can be submitted to the server for file upload;
3.img_upload_process.php is used for processing After the file is successfully uploaded, the successfully uploaded and saved file path is returned to the hidden field in the form;
4. When the form submit button is clicked, JS sets the form action to the form_process.php file that receives the form data, and the target setting of the form for_self.
Form: 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='0' width='0' height='0' name="uploadframe"></iframe> <input type="hidden" id="save_path" name="save_path" /> <span id="loading"></span> <br /> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/194/bf5b437281da9920f0761ec19c1de6a0-0.jpg?x-oss-process=image/resize,p_40" class="lazy" style="max-width:90%"A case study on how to asynchronously upload an iframe in a php form file" > <br /> <input type="submit" name="submitted" value="提交" onclick="formSubmit(this.form)" /> </form> <script> function startUpload(formObj){ document.getElementById('loading').innerHTML = '上传中...'; formObj.action = 'img_upload_process.php'; formObj.target = 'uploadframe'; formObj.submit(); } function formSubmit(formObj) { formObj.action = 'form_process.php'; formObj.target = '_self'; //清空文件上传内容,防止重复提交 var fileObj = document.getElementById('avator') ; // for IE, Opera, Safari, Chrome if (fileObj.outerHTML) { fileObj.outerHTML = fileObj.outerHTML; } else { // FF(包括3.5) fileObj.value = ""; } formObj.submit(); } </script> </body> </html>
Process file upload: img_upload_process.php
<?php include 'Upload.class.php'; $file = $_FILES['avator']; $upload = new Upload();//上传工具类对象 if($save_path = $upload->up($file)){//上传成功 echo <<<STR <script> window.parent.document.getElementById('uploaded_img').src = "$save_path"; window.parent.document.getElementById('loading').innerHTML = '上传成功'; window.parent.document.getElementById('save_path').value = "$save_path"; </script> STR; }else{ $error = $upload->error(); echo <<<STR <script> window.parent.document.getElementById('uploaded_img').src = ""; window.parent.document.getElementById('loading').innerHTML = "上传失败: $error"; </script> STR; }
File upload tool class: Upload.class.php
<?php class Upload{ private $path; //文件上传目录 private $max_size; //上传文件大小限制 private $errno; //错误信息号 private $mime = array('image/jpeg','image/png','image/gif');//允许上传的文件类型 /** * 构造函数, * @access public * @param $path string 上传的路径 */ public function __construct($path = './' ){ $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['tmp_name'])) { $this->errno = 5; //设置错误信息号为5,表示非法上传 return false; } */ //判断是否从浏览器端成功上传到服务器端 if ($file['error'] == 0) { # 上传到临时文件夹成功,对临时文件进行处理 //上传类型判断 if (!in_array($file['type'], $this->mime)) { # 类型不对 $this->errno = -1; return false; } //判断文件大小 if ($file['size'] > $this->max_size) { # 大小超出配置文件的中的上传限制 $this->errno = -2; return false; } //获取存放上传文件的目录 $sub_path = date('Ymd').'/'; if (!is_dir($this->path . $sub_path)) { # 不存在该目录,创建之 mkdir($this->path . $sub_path); } //文件重命名,由当前日期 + 随机数 + 后缀名 $file_name = date('YmdHis').uniqid().strrchr($file['name'], '.'); //准备就绪了,开始上传 if (move_uploaded_file($file['tmp_name'], $this->path . $sub_path . $file_name)) { # 移动成功 return $sub_path . $file_name; } else { # 移动失败 $this->errno = -3; return false; } } else { # 上传到临时文件夹失败,根据其错误号设置错误号 $this->errno = $file['error']; return false; } } /** * 多文件上传方法 * @access public * @param $file array 包含上传文件信息的数组,是一个二维数组 * @return array 成功返回上传的文件名构成的数组, ?如果有失败的则不太好处理了 */ public function multiUp($files){ //在多文件上传时,上传文件信息 又是一个多维数组,如$_FILES['userfile']['name'][0],$_FILES['userfile']['name'][1] //我们只需要遍历该数组,得到每个上传文件的信息,依次调用up方法即可 foreach ($files['name'] as $key => $value) { # code... $file['name'] = $files['name'][$key]; $file['type'] = $files['type'][$key]; $file['tmp_name'] = $files['tmp_name'][$key]; $file['error'] = $files['error'][$key]; $file['size'] = $files['size'][$key]; //调用up方法,完成上传 $filename[] = $this->up($file); } return $filename; } /** * 获取错误信息,根据错误号获取相应的错误提示 * @access public * @return string 返回错误信息 */ public function error(){ switch ($this->errno) { case -1: return '请检查你的文件类型,目前支持的类型有'.implode(',', $this->mime); break; case -2: return '文件超出系统规定的大小,最大不能超过'. $this->max_size; break; case -3: return '文件移动失败'; break; case 1: return '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值,其大小为'.ini_get('upload_max_filesize'); break; case 2: return '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值,其大小为' . $_POST['MAX_FILE_SIZE']; break; case 3: return '文件只有部分被上传'; break; case 4: return '没有文件被上传'; break; case 5: return '非法上传'; break; case 6: return '找不到临时文件夹'; break; case 7: return '文件写入临时文件夹失败'; break; default: return '未知错误,灵异事件'; break; } } }
Processing form submission: form_process.php
<?php var_dump($_REQUEST); var_dump($_FILES);
Click the form submit button Result:
The above is the detailed content of A case study on how to asynchronously upload an iframe in a php form file. For more information, please follow other related articles on the PHP Chinese website!

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools