界面样式我是参考了一个国外的相册网站,改动不大,只是把鸟语转换成中文,以及上传时的样式也进行了改动,之所以选这个的原因就是,我很容易做扩展,它支持3种方式添加图片,一种拖拽上传,一种常规的选">
Home > Web Front-end > H5 Tutorial > body text

html5 drag and drop upload image example demonstration_html5 tutorial skills

WBOY
Release: 2016-05-16 15:49:48
Original
1679 people have browsed it

Because the title is about an example, I won’t explain it this time, because I pieced together this example by referring to about 5 or 6 drag-and-drop uploaded plug-ins and demos, and then put the best ones among them. The place was picked out, and finally it became such an example. Let’s take a look at it together (the address cannot be guaranteed to be valid for a long time. If it is invalid, please click the demo download at the end of the article):

I am referring to the interface style. A foreign photo album website has not changed much. It just converted the bird songs into Chinese and changed the style when uploading. The reason why I chose this one 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 browse it with IE browser. If it does not support HTML5, there is no prompt to drag and drop to upload html5 drag and drop upload image example demonstration_html5 tutorial skillss, as shown in the picture:

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 html5 drag and drop upload image example demonstration_html5 tutorial skills information to the background and then perform corresponding processing, such as compression, cropping, etc. So let’s take a look at the js implementation code first.

Copy code
The code is as follows:

$().ready(function() {
if($.browser.safari || $.browser.mozilla){
$('#dtb-msg1 .compatible').show();
$('#dtb-msg1 . notcompatible').hide();
$('#drop_zone_home').hover(function(){
$(this).children('p').stop().animate({top:' 0px'},200);
},function(){
$(this).children('p').stop().animate({top:'-44px'},200);
});
//Function implementation
$(document).on({
dragleave:function(e){
e.preventDefault();
$('.dashboard_target_box ').removeClass('over');
},
drop:function(e){
e.preventDefault();
//$('.dashboard_target_box').removeClass(' over');
},
dragenter:function(e){
e.preventDefault();
$('.dashboard_target_box').addClass('over');
} ,
dragover:function(e){
e.preventDefault();
$('.dashboard_target_box').addClass('over');
}
});
var box = document.getElementById('target_box');
box.addEventListener("drop",function(e){
e.preventDefault();
//Get the file list
var fileList = e.dataTransfer.files;
var img = document.createElement('img');
//Detect whether it is an operation of dragging files to the page
if(fileList.length == 0) {
$('.dashboard_target_box').removeClass('over');
return;
}
//Detect whether the file is an html5 drag and drop upload image example demonstration_html5 tutorial skills
if(fileList[0].type. indexOf('html5 drag and drop upload image example demonstration_html5 tutorial skills') === -1){
$('.dashboard_target_box').removeClass('over');
return;
}
if($.browser.safari ){
//Chrome8
img.src = window.webkitURL.createObjectURL(fileList[0]);
}else if($.browser.mozilla){
//FF4
img.src = window.URL.createObjectURL(fileList[0]);
}else{
//Instantiate the file reader object
var reader = new FileReader();
reader.onload = function(e){
img.src = this.result;
$(document.body).appendChild(img);
}
reader.readAsDataURL(fileList[0]);
}
var xhr = new XMLHttpRequest();
xhr.open("post", "test.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest ");
xhr.upload.addEventListener("progress", function(e){
$("#dtb-msg3").hide();
$("#dtb-msg4 span" ).show();
$("#dtb-msg4").children('span').eq(1).css({width:'0px'});
$('.show ').html('');
if(e.lengthComputable){
var loaded = Math.ceil((e.loaded / e.total) * 100);
$("#dtb -msg4").children('span').eq(1).css({width:(loaded*2) 'px'});
}
}, false);
xhr. addEventListener("load", function(e){
$('.dashboard_target_box').removeClass('over');
$("#dtb-msg3").show();
$ ("#dtb-msg4 span").hide();
var result = jQuery.parseJSON(e.target.responseText);
alert(result.filename);
$('.show' ).append(result.img);
}, false);
var fd = new FormData();
fd.append('xfile', fileList[0]);
xhr. send(fd);
},false);
}else{
$('#dtb-msg1 .compatible').hide();
$('#dtb-msg1 .notcompatible ').show();
}
});

At the beginning, I first determined the browser type, because as mentioned just now, different browsers see different interfaces. The main implementation code starts from "Function Implementation". I won't go into details about why this operation is done in this way and what the principle is. You can refer to this article: "Detailed explanation of drag and drop upload on Renren homepage (HTML5 Drag&Drop , FileReader API, formdata)", but the code for the ajax upload part is still a bit different, because Renren's one seems a bit troublesome, so I looked for another way.
The last part is to upload the PHP code. Here I just provide a reference, you can write it yourself according to the needs of the project.

Copy code
The code is as follows:

$r = new stdClass();
header('content-type: application/json');
$maxsize = 10; //Mb
if($_FILES['xfile']['size'] > ($maxsize * 1048576 )){
$r->error = "The html5 drag and drop upload image example demonstration_html5 tutorial skills size does not exceed $maxsize MB";
}
$folder = 'files/';
if(!is_dir($folder)) {
mkdir($folder);
}
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if(! is_dir($folder)){
mkdir($folder);
}
if(preg_match('/html5 drag and drop upload image example demonstration_html5 tutorial skills/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('html5 drag and drop upload image example demonstration_html5 tutorial skills/png', 'html5 drag and drop upload image example demonstration_html5 tutorial skills/gif', 'html5 drag and drop upload image example demonstration_html5 tutorial skills/jpeg');
if(in_array($_FILES['xfile ']['type'], $types)){
$source = file_get_contents($_FILES["xfile"]["tmp_name"]);
html5 drag and drop upload image example demonstration_html5 tutorial skillsresize($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 = 'html5 drag and drop upload image example demonstration_html5 tutorial skills';
echo json_encode($r);
function html5 drag and drop upload image example demonstration_html5 tutorial skillsresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
$quality = $ quality ? $quality : 80;
$html5 drag and drop upload image example demonstration_html5 tutorial skills = html5 drag and drop upload image example demonstration_html5 tutorial skillscreatefromstring($source);
if ($html5 drag and drop upload image example demonstration_html5 tutorial skills) {
// Get dimensions
$w = html5 drag and drop upload image example demonstration_html5 tutorial skillssx($html5 drag and drop upload image example demonstration_html5 tutorial skills);
$h = html5 drag and drop upload image example demonstration_html5 tutorial skillssy($html5 drag and drop upload image example demonstration_html5 tutorial skills);
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 = html5 drag and drop upload image example demonstration_html5 tutorial skillscreatetruecolor(round($new_width), round($new_height));
html5 drag and drop upload image example demonstration_html5 tutorial skillscopyresampled($new, $html5 drag and drop upload image example demonstration_html5 tutorial skills, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
// Crop
if ($crop) {
$crop = html5 drag and drop upload image example demonstration_html5 tutorial skillscreatetruecolor($width ? $width : $new_width , $height ? $height : $new_height);
html5 drag and drop upload image example demonstration_html5 tutorial skillscopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
//($y_mid - ($height * .5))
}
// Output
// Enable interlancing [for progressive JPEG]
html5 drag and drop upload image example demonstration_html5 tutorial skillsinterlace($crop ? $crop : $new, true);
$dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
if ($dext == '') {
$dext = $ext;
$destination .= '.' . $ext;
}
switch ($dext) {
case 'jpeg':
case 'jpg':
html5 drag and drop upload image example demonstration_html5 tutorial skillsjpeg($crop ? $crop : $new, $destination, $quality);
break;
case 'png':
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs ($pngQuality));
html5 drag and drop upload image example demonstration_html5 tutorial skillspng($crop ? $crop : $new, $destination, $pngQuality);
break;
case 'gif':
html5 drag and drop upload image example demonstration_html5 tutorial skillsgif($crop ? $crop : $new, $destination);
break;
}
@html5 drag and drop upload image example demonstration_html5 tutorial skillsdestroy($html5 drag and drop upload image example demonstration_html5 tutorial skills);
@html5 drag and drop upload image example demonstration_html5 tutorial skillsdestroy($new);
@html5 drag and drop upload image example demonstration_html5 tutorial skillsdestroy($crop);
}
}

PHP will eventually return an array in JSON format. The information I returned is the html5 drag and drop upload image example demonstration_html5 tutorial skills address, name, and the html code of the img. Finally, the json array is obtained and processed in js. At this point, the operation is over.
As mentioned at the beginning of the article, there are also click-to-select file uploads and network html5 drag and drop upload image example demonstration_html5 tutorial skillss. Since these two do not fall within the scope of this topic, I will not talk about them. Moreover, these two functions are not troublesome to implement.
demo download
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!