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

A brief talk about the diff algorithm in Vue

Table of contents Overview Virtual Dom principle ...

WeChat applet realizes left-right linkage

This article shares the specific code for WeChat ...

Pure CSS to achieve hover image pop-out pop-up effect example code

Implementation principle The main graphics are co...

Connector configuration in Tomcat

JBoss uses Tomcat as the Web container, so the co...

Analysis of the advantages and disadvantages of MySQL stored procedures

MySQL version 5.0 began to support stored procedu...

How to expand the disk space of Linux server

Table of contents Preface step Preface Today I fo...

Docker creates MySQL explanation

1. Download MySQL Image Command: docker pull mysq...

JavaScript code to implement Weibo batch unfollow function

A cool JavaScript code to unfollow Weibo users in...

3 ways to correctly modify the maximum number of connections in MySQL

We all know that after the MySQL database is inst...

Develop calculator example code using native javascript

The main function of a calculator is to perform n...

Using group by in MySQL always results in error 1055 (recommended)

Because using group by in MySQL always results in...

Native js to achieve simple carousel effect

This article shares the specific code of js to ac...

Mysql queries the transactions being executed and how to wait for locks

Use navicat to test and learn: First use set auto...