Table of Contents
php+html5实现无刷新图片上传教程,
您可能感兴趣的文章:
Home php教程 php手册 php+html5实现无刷新图片上传教程,

php+html5实现无刷新图片上传教程,

Jun 13, 2016 am 08:47 AM
html5 php upload picture No refresh

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>
Copy after login

样式如下图

接下来是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>
Copy after login

接下来是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));
Copy after login

选择文件然后点击上传的效果如下图

以上就是整个图片上传的代码。当然对于PHP的部分还有很多可以优化的地方,比如文件名部分,可以重命名,以保证相同文件名上传以后的文件名是不同的等等。这种上传方式我也是刚开始使用,当初是受Node.js做上传的的启发,然后尝试着应用于PHP,没想到还真能上传成功。

希望大家也可以按照此方法实现图片上传。

您可能感兴趣的文章:

  • PHP图片上传类带图片显示
  • 简单的PHP图片上传程序
  • php ajax无刷新上传图片实例代码
  • php 图片上传类代码
  • thinkphp实现图片上传功能分享
  • 使用PHP和HTML5 FormData实现无刷新文件上传教程
  • ThinkPHP结合AjaxFileUploader实现无刷新文件上传的方法
  • php多个文件及图片上传实例详解
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

See all articles