html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법

巴扎黑
풀어 주다: 2017-03-19 14:05:42
원래의
1553명이 탐색했습니다.

[소개] html5에서 파일 업로드를 구현하는 기능을 소개하는 글입니다. 필요한 학생들이 참고하시면 됩니다. 인터페이스 스타일은 외국 사진첩 사이트를 참고했는데, 업로드할 때 새소리만 중국어로 바꾸고 스타일을 바꿨어요.

이번 글에서는 자세한 내용은 HTML5의 파일 업로드 기능에 대한 소개입니다. 필요한 학생들이 참고할 수 있습니다.

인터페이스 스타일은 외국 사진첩 사이트를 참고해서 변경사항은 크지 않았는데 그냥 새소리만 중국어로 변환하고 업로드 스타일도 바꿨습니다. 이것을 선택한 이유는 확장이 쉽기 때문입니다. 사진을 추가하는 방법은 드래그 앤 드롭 업로드, 파일 업로드 일반 선택, 네트워크 사진 추가 등 3가지가 있습니다. 세 가지 업로드 모드를 교묘하게 통합하고 있으며, HTML5를 지원하지 않는 경우 그림과 같이 드래그 앤 드롭하여 이미지를 업로드하라는 메시지가 표시되지 않습니다.

드래그 앤 드롭 업로드에서 가장 중요한 부분은 코드의 js 부분으로, 이는 70%의 기능을 구현하고 나머지 30%는 단지 이미지 정보를 백그라운드에 제출한 후 수행하는 것입니다. 압축 및 자르기와 같은 해당 처리가 너무 많습니다. 그럼 먼저 js 구현 코드를 살펴보겠습니다.

 代码如下 复代码





无标题文档


<script><br/>$().ready(function() {<br/> if($.browser.safari || $.browser.mozilla){<br/>  $('#dtb-msg1 . Compatible').show();<br/>  $('#dtb-msg1 .not Compatible').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('html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법') === -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 스팬").show();<br/>    $("#dtb-msg4").children('span').eq(1).css({너비:'0px'}) ;<br/>    $('.show').html('');<br/>    if(e.lengthComputable){<br/>     var added = 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-msg4span").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 .not Compatible').show();<br/> }<br/>});<br/></script>



 


  

选择你의 사진
开始上传


  


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


 
 

选择网络图文


 


  
  
 






test.php 파일

 代码如下 复代码

 $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);
 }
 $ 폴더 .= $_POST['폴더'] ? $_POST['폴더'] . '/' : '';
 if(!is_dir($folder)){
  mkdir($folder);
 }
 
 if(preg_match('/html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법/i', $_FILES['xfile']['type'])){
     $filename = $_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']) . 🎜> $types = Array('html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법/png', 'html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법/gif', 'html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법/jpeg');
 if(in_array($_FILES['xfile']['type'], $types)) {
  $source = file_get_contents($_FILES["xfile"]["tmp_name"]);
  html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법resize($source, $filename, $_POST['width'], $_POST['height'], $_POST['자르기'], $_POST['품질']);
 }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+php에서 파일 드래그 및 업로드 기능을 구현하는 방법';
 
 echo json_encode($r);
 
 함수 html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법resize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
     $quality = $quality ? $quality : 80;
     $html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법 = html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법createfromstring($source);
     if ($html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법) {
         / / 크기 가져오기
         $w = Imagesx($html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법);
         $h = Imagesy($html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법);
         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 = $ 너비 / $ratio;
                $new_width = $width;
            } else {
                $new_width = $height * $ratio;
                $new_height = $he ight;
             }
         } else {
             $new_width = $w;
             $new_height = $h;
         }
         $x_mid = $new_width * .5;  //가로 가운데
         $y_mid = $new_height * .5; //세로 중앙
         // 리샘플
         error_log('height: ' . $new_height . ' - width: ' . $new_width);
         $new = html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법createtruecolor(round($new_width), round($ new_height));
         html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법copyresampled($new, $html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
         // 자르기
         if ($crop) {
             $crop = html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법createtruecolor($width ? $width : $new_width, $height ? $height : $new_height);
             html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법copyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
            //($y_mid - ($height * .5))
         }
         // 출력
         // 인터랜싱 활성화 [프로그레시브 JPEG의 경우]
         html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법interlace($crop ? $crop : $new, true);
 
         $dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
if ($dext == '') {
             $dext = $ext;
             $destination .= '.' . $ext;
         }
         스위치($dext) {
             사례 'jpeg':
             사례 'jpg':
                html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법jpeg($crop ? : $new, $destination, $ 품질);
                 break;
             케이스 'png':
                $pngQuality = ($quality - 100) / 11.111111;
                 $ pngQuality = round(abs($pngQuality));
                 html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법png ($crop ? $crop : $new, $destination, $pngQuality);
                break;
             case 'gif':
               html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법gif($crop ? $crop : $new, $destination);
                break;
         }
         @html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법destroy($html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법);
         @html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법destroy($new);
         @html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법destroy($crop);
     }
 }
?> ;

위 내용은 html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!