php+html5实现无刷新图片上传教程,
php+html5实现无刷新图片上传教程,
本篇向大家介绍一种全新的上传图片的方式,利用html5的FileReader读取图片文件,然后将数据传输到服务器再使用PHP进行处理。实现过程如下(带图片预览功能)
前端html代码 upload,html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>上传</title> <script type="text/javascript" src="js/jquery.min.js"></script> <style> .upload{ width:300px; height:200px; position:relative; } .upload input[type='file']{ position:absolute; width:70px; top:0; left:0; z-index:10; opacity:0; filter:alpha(opacity=0); } .upload input.selbutton{ width:70px; height:30px; background:#cf001b; color:#FFF; font-size:14px; position:absolute; top:0;left:0; z-index:9; border:none; cursor:pointer; } .upload input.upbutton{ width:70px; height:30px; background:#cf001b; color:#FFF; font-size:14px; position:absolute; top:50px;left:0; z-index:10; border:none; cursor:pointer; } </style> </head> <body> <div class='upload'> <input type="file" name="file" /> <input type="button" name="selbutton" class="selbutton" value="选择文件" /> <input type="button" name="upbutton" class="upbutton" value="上传" /> </div> <div class='previews'> <img class="image_thumb lazy" src="/static/imghw/default1.png" data-src="#" alt="图片预览"/> </div> </body> </html>
样式如下图
接下来是js代码
<script type="text/javascript"> $(".upbutton").click(function(){ //定义允许上传的图片格式 在前台就可以直接判断,不合法的格式将不会上传 var filetype = ['jpg','jpeg','png','gif']; if($('.image').get(0).files){ fi = $('.image').get(0).files[0]; //得到文件信息 //判断文件格式是否是图片 如果不是图片则返回false var fname = fi.name.split('.'); if(filetype.indexOf(fname[1].toLowerCase()) == -1){ alert('文件格式不支持'); return ; } //实例化h5的fileReader var fr = new FileReader(); fr.readAsDataURL(fi); //以base64编码格式读取图片文件 fr.onload = function(frev){ pic = frev.target.result; //得到结果数据 //开始上传之前,预览图片 $('.image_thumb').attr('src',pic); //使用ajax 利用post方式提交数据 $.post( 'handle.php', { message:pic, filename:fname[0], filetype:fname[1], filesize:fi.size }, function(data){ data = eval('('+data+')'); if(data.code == 1 || data.code == 2){ console.log('上传失败') }else if(data.code == 0){ console.log('上传成功') } } ); } } }) </script>
接下来是PHP处理代码 handle.php
$imgtype = array( 'gif'=>'gif', 'png'=>'png', 'jpg'=>'jpeg', 'jpeg'=>'jpeg' ); //图片类型在传输过程中对应的头信息 $message = $_POST['message']; //接收以base64编码的图片数据 $filename = $_POST['filename']; //接收文件名称 $ftype = $_POST['filetype']; //接收文件类型 //首先将头信息去掉,然后解码剩余的base64编码的数据 $message = base64_decode(substr($message,strlen('data:image/'.$imgtype[strtolower($ftype)].';base64,'))); $filename = $filename.".".$ftype; $furl = "D:/now/"; //开始写文件 $file = fopen($furl.$filename,"w"); if(fwrite($file,$message) === false){ echo json_encode(array('code'=>1,'con'=>'failed')); exit; } echo json_encode(array('code'=>0,'con'=>$filename));
选择文件然后点击上传的效果如下图
以上就是整个图片上传的代码。当然对于PHP的部分还有很多可以优化的地方,比如文件名部分,可以重命名,以保证相同文件名上传以后的文件名是不同的等等。这种上传方式我也是刚开始使用,当初是受Node.js做上传的的启发,然后尝试着应用于PHP,没想到还真能上传成功。
希望大家也可以按照此方法实现图片上传。
您可能感兴趣的文章:
- PHP图片上传类带图片显示
- 简单的PHP图片上传程序
- php ajax无刷新上传图片实例代码
- php 图片上传类代码
- thinkphp实现图片上传功能分享
- 使用PHP和HTML5 FormData实现无刷新文件上传教程
- ThinkPHP结合AjaxFileUploader实现无刷新文件上传的方法
- php多个文件及图片上传实例详解

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
