How to Upload an Excel File to Php From Ajax With Post and $_files
Read Time: 9 mins Languages:
I can't seem to accomplish the cease of the fun stuff you can do with web technologies. Today, I'm going to show yous how to upload files via AJAX.
First, we'll see how to upload files using vanilla JavaScript. And later on, I'll show how you lot could utilise the DropzoneJS library to implement elevate-and-driblet file uploads.
Looking for a Quick Solution?
If you're looking for a quick solution, there's a great collection of file upload scripts and applications over at CodeCanyon.



How to Upload a File With Vanilla JavaScript
There are three principal components to our project:
- the
multiple
attribute on the fileinput
element - the
FileReader
object from the new File API - the
FormData
object fromXMLHttpRequest
We utilize themultiple
attribute to allow the user to select multiple files for upload (multiple file upload will work commonly even ifFormData
isn't available). Every bit you'll run into,FileReader
allows usa to show the user thumbnails of the files they're uploading (we'll be expecting images).
For older browsers that don't supportFormData
orFileReader
, the upload behavior will fall back to a normal, non-AJAX file upload.
With that out of the fashion, let's get coding!
Stride i: The Markup and Styling
Permit'south start with some basic markup and styling. Of form, this isn't the main part of this tutorial—I won't treat you like a newbie.
The HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>HTML5 File API</title> <link rel="stylesheet" href="style.css" /> </head> <trunk> <div id="main"> <h1>Upload Your Images</h1> <class method="mail" enctype="multipart/form-data" action="upload.php"> <input type="file" proper noun="images" id="images" multiple /> <button type="submit" id="btn">Upload Files!</push> </class> <div id="response"></div> <ul id="image-list"> </ul> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script src="upload.js"></script> </body> </html>
Pretty bones, eh? We've got a form that posts toupload.php, which we'll wait at in a 2nd, and a single input element, of typefile
. Notice that it has the booleanmultiple
attribute, which allows the user to select multiple files at once.
That's really all there is to encounter here. Let'southward movement on.
The CSS
body { font: 14px/one.5 helvetica-neue, helvetica, arial, san-serif; padding:10px; } h1 { margin-tiptop:0; } #main { width: 300px; margin:car; background: #ececec; padding: 20px; border: 1px solid #ccc; } #image-list { list-way:none; margin:0; padding:0; } #image-list li { background: #fff; edge: 1px solid #ccc; text-marshal:center; padding:20px; margin-bottom:19px; } #image-list li img { width: 258px; vertical-align: heart; border:1px solid #474747; }
No shockers here—we're only creating some basic styling for our upload form.
Step 2: The PHP
Nosotros need to be able to handle the file uploads on the back end every bit well, so let'south encompass that side by side.
upload.php
<?php foreach ($_FILES["images"]["error"] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $name = $_FILES["images"]["proper noun"][$cardinal]; move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['proper name'][$cardinal]); } } repeat "<h2>Successfully Uploaded Images</h2>";
Bear in mind that these were the first lines of PHP I'd written in easily a twelvemonth. You should probably be doing a fleck more for security; withal, we're simply making sure that at that place are no upload errors. If that's the instance, we use the built-inmove_uploaded_file
to move information technology to anuploads
binder. Don't forget to make certain that the binder is writable.
So, right now, we should have a working upload form. You choose an prototype (multiple, if yous want to and your browser lets yous), click theUpload Files! button, and you get the messageSuccessfully Uploaded Images .
Here'south what our mini-project looks like so far:



But, come on, it'due south 2020: we want more than that. You'll detect that we've linked up jQuery and anupload.js file. Permit's crack that open up at present.
Footstep iii: The JavaScript
Let'southward dive right into the JavaScript lawmaking for file uploading!
(function () { var input = document.getElementById("images"), formdata = false; if (window.FormData) { formdata = new FormData(); document.getElementById("btn").style.display = "none"; } }();
Hither's what we beginning with. We create 2 variables:input
is our file input element, and formdata
volition exist used to send the images to the server if the browser supports that. Nosotros initialize it toimitation
and then check to run across if the browser supportsFormData
. If information technology does, we create a newFormData
object. Too, if nosotros can submit the images with AJAX, we don't demand theUpload Images! button, and then we can hide it. Why don't nosotros need it? Well, we're going to automobile-magically upload the images immediately after the user selects them.
The residuum of the JavaScript volition go within your anonymous self-invoking office. We side by side create a little helper function that will show the images once the browser has them:
function showUploadedItem (source) { var list = certificate.getElementById("image-list"), li = certificate.createElement("li"), img = document.createElement("img"); img.src = source; li.appendChild(img); list.appendChild(li); }
The part takes one parameter: the image source (we'll come across how nosotros get that shortly). Then, we simply find the list in our markup and create a list item and paradigm. We prepare the image source to the source we received, put the paradigm in the list item, and put the list item in the list. Voila!
Next, nosotros have to actually take the images, display them, and upload them. As we've said, we'll practise this when theonchange
event is fired on the input element.
if (input.addEventListener) { input.addEventListener("alter", function (evt) { var i = 0, len = this.files.length, img, reader, file; document.getElementById("response").innerHTML = "Uploading . . ." for ( ; i < len; i++ ) { file = this.files[i]; if (!!file.type.match(/prototype.*/)) { } } }, false); }
So, what do we want to practise when the user has selected files? First, we create a few variables. The only important one right now islen = this.files.length
. The files that the user has selected will be attainable from the objectthis.files
. Correct now, we're only concerned with thelength
property, so we tin loop over the files... and that is exactly what we're doing side by side. Inside our loop, we set the electric current file tofile
for ease of access. The adjacent thing we practice is confirm that the file is an paradigm. We can practise this by comparing the type
property with a regular expression. Nosotros're looking for a blazon that starts with "image" and is followed by anything. (The double-bang in front just converts the result to a boolean.)
And then, what practise we practise if we accept an prototype on our easily?
if ( window.FileReader ) { reader = new FileReader(); reader.onloadend = office (e) { showUploadedItem(e.target.result); }; reader.readAsDataURL(file); } if (formdata) { formdata.append("images[]", file); }
We check to see if the browser supports creatingFileReader
objects. If it does, we'll create one.
Here's how nosotros use aFileReader
object: Nosotros're going to pass ourfile
object to thereader.readAsDataURL
method. This creates a data URL for the uploaded image. It doesn't work the way you might wait, though. The information URL isn't passed dorsum from the function. Instead, information technology will be function of an event object.
With that in mind, we'll need to register a role on thereader.onloadend
event. This role takes an event object, by which we get the data URL: it's ateast.target.result
. We're but going to pass this data URL to our showUploadedItem
function (which we wrote above).
Adjacent, we bank check for theformdata
object. Recall, if the browser supportsFormData
,formdata
will be aFormData
object; otherwise, it will befalse
. So, if we have aFormData
object, we're going to call theappend
method. The purpose of aFormData
object is to hold values that you're submitting via a form, so the suspend
method simply takes a fundamental and a value. In our example, our central isimages[]
. By adding the square-brackets to the finish, nosotros make sure that each fourth dimension we append
another value, we're actually appending it to that array, instead of overwriting theepitome
property.
We're almost done. In our for loop, nosotros've displayed each of the images for the user and added them to theformdata
object. At present, we simply need to upload the images. Outside thefor
loop, here'due south the last piece of our puzzle:
if (formdata) { $.ajax({ url: "upload.php", type: "POST", data: formdata, processData: false, contentType: false, success: function (res) { document.getElementById("response").innerHTML = res; } }); }
Once again, we accept to brand sure nosotros haveFormData
support; if we don't, theUpload Files! button volition be visible, and that'southward how the user volition upload the photos. However, if we haveFormData
support, nosotros'll take care of uploading via AJAX. We're using jQuery to handle all the oddities of AJAX beyond browsers.
You're probably familiar with jQuery's$.ajax
method: you pass it an options object. Theurl
,blazon
, andsuccess
properties should be obvious. Thedata
property is ourformdata
object. Notice thoseprocessData
andcontentType
properties. Co-ordinate to jQuery's documentation,processData
istrue
past default, and will process and transform the information into a query string. We don't desire to do that, so we set this tofalse
. We're as well settingcontentType
tofalse
to make sure that information gets to the server as we await it to.
And that's it. Now, when the user loads the page, they come across this:



And subsequently they select the images, they'll see this:



And the images have been uploaded:

So that's how you tin upload files using the vanilla JavaScript. In the next section, we'll see how to implement file upload with the DropzoneJS library.
How to Use the DropzoneJS Library
The DropzoneJS library is a popular complimentary library which allows y'all to implement file uploads in the blink of an heart. It likewise supports drag-and-driblet file uploads along with a beautiful preview characteristic.
Let's accept a look at the following code, which implements the file upload functionality with DropzoneJS.
<!DOCTYPE html> <html> <head> <script src="./dropzone.js"></script> <link rel="stylesheet" href="./dropzone.css"> </head> <trunk> <form activeness="/upload.php" grade="dropzone"> <div class="fallback"> <input name="images" type="file" multiple /> </div> </course> </body>
You'll accept to download thedropzone.js anddropzone.css files locally first.
Apart from that, you simply need to use thedropzone
class in the form tag, and the DropzoneJS library will handle the remainder!
Let'southward come across what information technology looks similar when you lot load information technology in your browser.



Every bit you can see, at that place's a section which allows you to driblet files on information technology. Alternatively, you could also select files from your computer by using the default file pick dialog box. Become ahead and driblet a few paradigm files on it, and it should present you with a squeamish preview, as shown in the following screenshot.



Doesn't that look astonishing, with but a few lines of lawmaking? In fact, the DropzoneJS library also allows you to customize the UI and other stuff. I would encourage you to bank check the configuration options provided past this library.
Apart from this, there'due south the filepond library, which is also a popular file upload library you could utilise. It provides features like elevate and drop, progress bar, previews, and reordering.
That's a Wrap!
Uploading files via AJAX is pretty cool, and information technology's not bad that these new technologies support that without the demand for lengthy hacks.
Learn JavaScript With a Free Course
If you want to master JavaScript, be certain to bank check out our complimentary class to larn the complete A-Z of modern JavaScript fundamentals.
In this class, you'll larn all of the essential concepts of the JavaScript language. That'due south right: all of them! Including the nigh important recent improvements to the language, in JavaScript ES6 (ECMAScript 2015) and JavaScript ES7 (ECMAScript 2016).
You'll start with the very fundamentals of the language: variables and datatypes. Then in each lesson you'll build cognition, from data structures similar arrays and maps to loops, control structures, and functions. Forth with the basics of the linguistic communication, you'll also larn some key congenital-in APIs for manipulating data, AJAX, and working with the web browser DOM. Finally, y'all'll go a look at some of the most powerful and widely used spider web APIs that are supported by all modern browsers.
This post has been updated with contributions from Sajal Soni. Sajal belongs to India and he loves to spend time creating websites based on open source frameworks.
Did you lot notice this post useful?
Source: https://code.tutsplus.com/tutorials/uploading-files-with-ajax--net-21077
0 Response to "How to Upload an Excel File to Php From Ajax With Post and $_files"
إرسال تعليق