⬆️ ⬇️

Uploading images to the server using HTML5 + jQuery + PHP

Good day!



Surely, many people saw in the WP engine a function of transferring files from the desktop to the browser window and their further upload to the server. When I saw this, I wondered how it was organized. Then I climbed into the wilds, I almost got lost, but I still found a solution. It turns out everything is very simple.



What do we need?



Just a little knowledge of HTML5 + jQuery + PHP.



Here we go.



')

To begin, let's write down the work of our mini application.



1) The user selects one or several files on his PC (in our case graphic files) and drags these files into a browser window that supports the Drag & Drop API (more precisely, the user transfers the files to a designated download space).

2) After that, we have an event triggered and using the API we get information about the uploaded files and store them in temporary memory.

3) Next, using the new sendAsBinary transfer method of the XMLHttpRequest object, we send our file from the temporary memory to the server.



Perhaps, the above described is not entirely clear, but now everyone will understand everything.



We will not reinvent the bicycle by taking jQuery FileDrop plugin. But since we did not invent a bicycle, there is one drawback: this plugin only works in Firefox and Chrome browsers. This is not surprising, because we are writing an application using HTML5, and not all major browsers support it. But let's not dwell on this.



Create an index.html file

With this content:

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"> <title>    Drag & Drop API.</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <!--          --> <div id="dropbox"> <!--             --> <span class="message">    </span> </div> <!--   jQuery --> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <!--   FileDrop --> <script src="js/jquery.filedrop.js"></script> <!--      js     --> <script src="js/script.js"></script> </body> </html> 




Go ahead ..



Now we will create our handler, in which we combine the action of the FileDrop plugin and the jQuery library, as well as create some small restrictions.

 $(function(){ var dropbox = $('#dropbox'), message = $('.message', dropbox); dropbox.filedrop({ paramname:'pic', maxfiles: 5, maxfilesize: 2, url: 'post_file.php', uploadFinished:function(i,file,response){ $.data(file).addClass('done'); }, error: function(err, file) { switch(err) { case 'BrowserNotSupported': showMessage('    HTML5!'); break; case 'TooManyFiles': alert('   1    5 '); break; case 'FileTooLarge': alert(file.name+'  .     2.'); break; default: break; } }, beforeEach: function(file){ if(!file.type.match(/^image\//)){ alert('   !!!!'); return false; } }, uploadStarted:function(i, file, len){ createImage(file); }, progressUpdated: function(i, file, progress) { $.data(file).find('.progress').width(progress); } }); var template = '<div class="preview">'+ '<span class="imageHolder">'+ '<img />'+ '<span class="uploaded"></span>'+ '</span>'+ '<div class="progressHolder">'+ '<div class="progress"></div>'+ '</div>'+ '</div>'; function createImage(file){ var preview = $(template), image = $('img', preview); var reader = new FileReader(); image.width = 100; image.height = 100; reader.onload = function(e){ image.attr('src',e.target.result); }; reader.readAsDataURL(file); message.hide(); preview.appendTo(dropbox); $.data(file,preview); } function showMessage(msg){ message.html(msg); } }); 




Now, let's lay out our application and create it by creating a styles.css file (located in the source code archive)



On this, we end with the client part, and go to the server.

Let's write a small php handler:

 <?php //    function exit_status($str){ echo json_encode(array('status'=>$str)); exit; } function get_extension($file_name){ $ext = explode('.', $file_name); $ext = array_pop($ext); return strtolower($ext); } $upload_dir = 'uploads/'; //     $allowed_ext = array('jpg','jpeg','png','gif'); //   if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){ exit_status('     !'); } if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){ $pic = $_FILES['pic']; if(!in_array(get_extension($pic['name']),$allowed_ext)){ exit_status('   : '.implode(',',$allowed_ext)); } //           ,       if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){ exit_status('   !'); } } exit_status('    '); ?> 


That's all! Now we start our local server, we open the site and we test it. It should look like this:

1) Just open browser page



2) Download 1st file



3) Download 2nd file



4) Download 6 files





That's all. If we check the uploads folder, then you will see all the downloaded pictures in it.



Sources here

Demo version here

Thank you for your attention!



Ps. As a goal, I did not set myself the task of making a fully working application for uploading files to the server and further viewing them. I just wanted to demonstrate a fairly new way of loading, which I think was interesting to many.

Source: https://habr.com/ru/post/136694/



All Articles