File upload via HTML5 on mobile

File upload via HTML5 on mobile

Most of the time, plug-ins are used to upload files on the PC, and it doesn't matter if flash is introduced. However, if various redundant plug-ins are still used on the mobile terminal, you will probably be criticized to death. The project needs to have the function of uploading pictures. Since H5 already has related interfaces and good compatibility, of course H5 is given priority to implement it.

The main technologies used are:

ajax

FileReader

FormData

HTML structure:

XML/HTML CodeCopy content to clipboard
  1. < div   class = "camera-area" >   
  2.        < form   enctype = "multipart/form-data"   method = "post" >   
  3.          < input   type = "file"   name = "fileToUpload"   class = "fileToUpload"   accept = "image/*"   capture = "camera" />   
  4.            < div   class = "upload-progress" > < span > </ span > </ div >   
  5.          </ form >   
  6.        < div   class = "thumb" > </ div >   
  7.    </ div >   
  8.   

The packaged upload.js depends on zepto

JavaScript CodeCopy content to clipboard
  1. ( function ($) {
  2. $.extend($.fn, {
  3. fileUpload: function (opts) {
  4.        this .each( function () {
  5.          var $self = $( this );
  6.          var doms = {
  7.            "fileToUpload" : $self.find( ".fileToUpload" ),
  8.            "thumb" : $self.find( ".thumb" ),
  9.            "progress" : $self.find( ".upload-progress" )
  10. };
  11.          var funs = {
  12.            //Select a file and get the file size. You can also get the file format here to restrict users from uploading files in non-required formats.   
  13.            "fileSelected" : function () {
  14.              var files = (doms.fileToUpload)[0].files;
  15.              var count = files.length;
  16.              for ( var index = 0; index < count; index++) {
  17.                var file = files[index];
  18.                var fileSize = 0;
  19.                if (file.size > 1024 * 1024)
  20. fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB' ;
  21.                else   
  22. fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB' ;
  23. }
  24. funs.uploadFile();
  25. },
  26.            // Upload files asynchronously   
  27. uploadFile: function () {
  28.              var fd = new FormData(); //Create a form data object   
  29.              var files = (doms.fileToUpload)[0].files;
  30.              var count = files.length;
  31.              for ( var index = 0; index < count; index++) {
  32.                var file = files[index];
  33. fd.append(opts.file, file); //Add the file to the form data   
  34. funs.previewImage(file); //Preview the image before uploading, you can also preview the txt file by other methods   
  35. }
  36.              var xhr = new XMLHttpRequest();
  37. xhr.upload.addEventListener( "progress" , funs.uploadProgress, false ); //Monitor upload progress   
  38. xhr.addEventListener( "load" , funs.uploadComplete, false );
  39. xhr.addEventListener( "error" , opts.uploadFailed, false );
  40. xhr.open( "POST" , opts.url);
  41. xhr.send(fd);
  42. },
  43.            //File preview   
  44. previewImage: function (file) {
  45.              var gallery = doms.thumb;
  46.              var img = document.createElement( "img" );
  47. img.file = file;
  48. doms.thumb.html(img);
  49.              // Use the FileReader method to display the image content   
  50.              var reader = new FileReader();
  51. reader.onload = ( function (aImg) {
  52.                return   function (e) {
  53. aImg.src = e.target.result;
  54. };
  55. })(img);
  56. reader.readAsDataURL(file);
  57. },
  58. uploadProgress: function (evt) {
  59.              if (evt.lengthComputable) {
  60.                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
  61. doms.progress.html(percentComplete.toString() + '%' );
  62. }
  63. },
  64.            "uploadComplete" : function (evt) {
  65. alert(evt.target.responseText)
  66. }
  67. };
  68. doms.fileToUpload.on( "change" , function () {
  69. doms.progress.find( "span" ).width( "0" );
  70. funs.fileSelected();
  71. });
  72. });
  73. }
  74. });
  75. })(Zepto);

Calling method:

JavaScript CodeCopy content to clipboard
  1. $( ".camera-area" ).fileUpload({
  2.          "url" : "savetofile.php" ,
  3.          "file" : "myFile"   
  4. });

PHP part:

PHP CodeCopy content to clipboard
  1. <?php
  2. if (isset( $_FILES [ 'myFile' ])) {
  3.      // Example:   
  4. writeLog( $_FILES );
  5. move_uploaded_file( $_FILES [ 'myFile' ][ 'tmp_name' ], "uploads/" . $_FILES [ 'myFile' ][ 'name' ]);
  6.      echo   'successful' ;
  7. }
  8. function writeLog( $log ){
  9.      if ( is_array ( $log ) || is_object ( $log )){
  10.          $log = json_encode( $log );
  11. }
  12.      $log = $log . "\r\n" ;
  13.   
  14.      file_put_contents ( 'log.log' , $log , FILE_APPEND);
  15. }
  16. ?>

The above is the full content of this article. I hope it will be helpful for everyone’s study.

Original text: http://www.cnblogs.com/hutuzhu/p/5254532.html

<<:  Tips for efficient use of CSS style sheets: Take full advantage of the power of style sheets

>>:  Example of converting webpack images to base64

Recommend

MySQL exposes Riddle vulnerability that can cause username and password leakage

The Riddle vulnerability targeting MySQL versions...

Solution to installing vim in docker container

Table of contents The beginning of the story Inst...

Detailed installation instructions for the cloud server pagoda panel

Table of contents 0x01. Install the Pagoda Panel ...

About the problem of writing plugins for mounting DOM in vue3

Compared with vue2, vue3 has an additional concep...

Python writes output to csv operation

As shown below: def test_write(self): fields=[] f...

How to export CSV file with header in mysql

Refer to the official document http://dev.mysql.c...

How to achieve the maximum number of connections in mysql

Table of contents What is the reason for the sudd...

Detailed explanation of the core concepts and basic usage of Vuex

Table of contents introduce start Install ① Direc...

How to implement Nginx reverse proxy for multiple servers

Nginx reverse proxy multiple servers, which means...

Two simple ways to remove text watermarks from web pages

<br /> When we browse certain websites and s...

How to decompress multiple files using the unzip command in Linux

Solution to the problem that there is no unzip co...

How to reset MySQL root password

Table of contents 1. Forgot the root password and...

Oracle VM VirtualBox installation of CentOS7 operating system tutorial diagram

Table of contents Installation Steps Environment ...

Detailed installation steps for MySQL 8.0.11

This article shares the installation steps of MyS...