찾다
웹 프론트엔드H5 튜토리얼html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법
html5+php에서 파일 드래그 및 업로드 기능을 구현하는 방법Mar 19, 2017 pm 02:05 PM
phpPHP 튜토리얼비디오 튜토리얼

[소개] 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전