Home > Web Front-end > H5 Tutorial > How to implement file drag and upload function in html5+php

How to implement file drag and upload function in html5+php

巴扎黑
Release: 2017-03-19 14:05:42
Original
1674 people have browsed it

[Introduction] This article introduces the function of implementing file upload in html5. Students in need can refer to it. I refer to a foreign photo album website for the interface style. The changes are not big. I just converted the bird songs into Chinese and changed the style when uploading. The reason why I chose this

This article introduces the details about This is an introduction to the function of file upload in HTML5. Students in need can refer to it.

How to implement file drag and upload function in html5+php

I refer to a foreign photo album website for the interface style. The changes are not big. I just converted the bird songs into Chinese and the upload style was also changed. The reason why I chose this is that it is easy for me to expand. It supports 3 ways to add pictures, one is drag and drop upload, one is regular selection of file upload, and the other is to add network pictures. It cleverly integrates three upload modes, and you can use IE browser to browse it. If it does not support HTML5, there is no prompt to drag and drop to upload images, as shown in the picture:

How to implement file drag and upload function in html5+php

The most important part of drag-and-drop upload is the js part of the code, which implements 70% of the functions. The other 30% is just to submit the image information to the background and then perform corresponding processing, such as compression and cropping. So much. So let’s take a look at the js implementation code first.

 代码如下 复制代码





无标题文档


<script><br/>$().ready(function(){<br/> if($.browser.safari || $.browser.mozilla){<br/>  $('#dtb-msg1 .compatible').show();<br/>  $('#dtb-msg1 .notcompatible').hide();<br/>  $('#drop_zone_home').hover(function(){<br/>   $(this).children('p').stop().animate({top:'0px'},200);<br/>  },function(){<br/>   $(this).children('p').stop().animate({top:'-44px'},200);<br/>  });<br/>  //功能实现<br/>  $(document).on({<br/>   dragleave:function(e){<br/>    e.preventDefault();<br/>    $('.dashboard_target_box').removeClass('over');<br/>   },<br/>   drop:function(e){<br/>    e.preventDefault();<br/>    //$('.dashboard_target_box').removeClass('over');<br/>   },<br/>   dragenter:function(e){<br/>    e.preventDefault();<br/>    $('.dashboard_target_box').addClass('over');<br/>   },<br/>   dragover:function(e){<br/>    e.preventDefault();<br/>    $('.dashboard_target_box').addClass('over');<br/>   }<br/>  });<br/>  var box = document.getElementById('target_box');<br/>  box.addEventListener("drop",function(e){<br/>   e.preventDefault();<br/>   //获取文件列表<br/>   var fileList = e.dataTransfer.files;<br/>   var img = document.createElement('img');<br/>   //检测是否是拖拽文件到页面的操作<br/>   if(fileList.length == 0){<br/>    $('.dashboard_target_box').removeClass('over');<br/>    return;<br/>   }<br/>   //检测文件是不是图片<br/>   if(fileList[0].type.indexOf('image') === -1){<br/>    $('.dashboard_target_box').removeClass('over');<br/>    return;<br/>   }<br/>   <br/>   if($.browser.safari){<br/>    //Chrome8+<br/>    img.src = window.webkitURL.createObjectURL(fileList[0]);<br/>   }else if($.browser.mozilla){<br/>    //FF4+<br/>    img.src = window.URL.createObjectURL(fileList[0]);<br/>   }else{<br/>    //实例化file reader对象<br/>    var reader = new FileReader();<br/>    reader.onload = function(e){<br/>     img.src = this.result;<br/>     $(document.body).appendChild(img);<br/>    }<br/>    reader.readAsDataURL(fileList[0]);<br/>   }<br/>   var xhr = new XMLHttpRequest();<br/>   xhr.open("post", "test.php", true);<br/>   xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");<br/>   xhr.upload.addEventListener("progress", function(e){<br/>    $("#dtb-msg3").hide();<br/>    $("#dtb-msg4 span").show();<br/>    $("#dtb-msg4").children('span').eq(1).css({width:'0px'});<br/>    $('.show').html('');<br/>    if(e.lengthComputable){<br/>     var loaded = Math.ceil((e.loaded / e.total) * 100);<br/>     $("#dtb-msg4").children('span').eq(1).css({width:(loaded*2)+'px'});<br/>    }<br/>   }, false);<br/>   xhr.addEventListener("load", function(e){<br/>    $('.dashboard_target_box').removeClass('over');<br/>    $("#dtb-msg3").show();<br/>    $("#dtb-msg4 span").hide();<br/>    var result = jQuery.parseJSON(e.target.responseText);<br/>    alert(result.filename);<br/>    $('.show').append(result.img);<br/>   }, false);<br/>   <br/>   var fd = new FormData();<br/>   fd.append('xfile', fileList[0]);<br/>   xhr.send(fd);<br/>  },false);<br/> }else{<br/>  $('#dtb-msg1 .compatible').hide();<br/>  $('#dtb-msg1 .notcompatible').show();<br/> }<br/>});<br/></script>



 


  

选择你的图片
开始上传


  


   拖动图片到这里
开始上传图片
  


 
 

选择网络图片


 


  
  
 






test.php file

 代码如下 复制代码

 $r = new stdClass();
 header('content-type: application/json');
 $maxsize = 10; //Mb
 if($_FILES['xfile']['size'] > ($maxsize * 1048576)){
  $r->error = "图片大小">图片大小不超过 $maxsize MB";
 }
 $folder = 'files/';
 if(!is_dir($folder)){
  mkdir($folder);
 }
 $folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
 if(!is_dir($folder)){
  mkdir($folder);
 }
 
 if(preg_match('/image/i', $_FILES['xfile']['type'])){
     $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . '.jpg';
 }else{
     $tld = split(',', $_FILES['xfile']['name']);
     $tld = $tld[count($tld) - 1];
     $filename = $_POST['value'] ? $_POST['value'] : $folder . sha1(@microtime() . '-' . $_FILES['xfile']['name']) . $tld;
 }
 
 $types = Array('image/png', 'image/gif', 'image/jpeg');
 if(in_array($_FILES['xfile']['type'], $types)){
  $source = file_get_contents($_FILES["xfile"]["tmp_name"]);
  imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
 }else{
  move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);
 }
 
 $path = str_replace('test.php', '', $_SERVER['SCRIPT_NAME']);
 
 $r->filename = $filename;
 $r->path = $path;
 $r->img = 'image';
 
 echo json_encode($r);
 
 function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
     $quality = $quality ? $quality : 80;
     $image = imagecreatefromstring($source);
     if ($image) {
         // Get dimensions
         $w = imagesx($image);
         $h = imagesy($image);
         if (($width && $w > $width) || ($height && $h > $height)) {
             $ratio = $w / $h;
             if (($ratio >= 1 || $height == 0) && $width && !$crop) {
                 $new_height = $width / $ratio;
                 $new_width = $width;
             } elseif ($crop && $ratio                  $new_height = $width / $ratio;
                 $new_width = $width;
             } else {
                 $new_width = $height * $ratio;
                 $new_height = $height;
             }
         } else {
             $new_width = $w;
             $new_height = $h;
         }
         $x_mid = $new_width * .5;  //horizontal middle
         $y_mid = $new_height * .5; //vertical middle
         // Resample
         error_log('height: ' . $new_height . ' - width: ' . $new_width);
         $new = imagecreatetruecolor(round($new_width), round($new_height));
         imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
         // Crop
         if ($crop) {
             $crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
             imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
             //($y_mid - ($height * .5))
         }
         // Output
         // Enable interlancing [for progressive JPEG]
         imageinterlace($crop ? $crop : $new, true);
 
         $dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
         if ($dext == '') {
             $dext = $ext;
             $destination .= '.' . $ext;
         }
         switch ($dext) {
             case 'jpeg':
             case 'jpg':
                 imagejpeg($crop ? $crop : $new, $destination, $quality);
                 break;
             case 'png':
                 $pngQuality = ($quality - 100) / 11.111111;
                 $pngQuality = round(abs($pngQuality));
                 imagepng($crop ? $crop : $new, $destination, $pngQuality);
                 break;
             case 'gif':
                 imagegif($crop ? $crop : $new, $destination);
                 break;
         }
         @imagedestroy($image);
         @imagedestroy($new);
         @imagedestroy($crop);
     }
 }
?>

The above is the detailed content of How to implement file drag and upload function in html5+php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template