Monday, November 30, 2020

Uploading Files With AJAX

Uploading Files With AJAX

I can’t seem to reach the end of the fun stuff you can do with web technologies. Today, I’m going to show you 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 could use the DropzoneJS library to implement drag-and-drop 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.

JavaScript File Loaders and Uploaders

How to Upload a File With Vanilla JavaScript

There are three main components to our project.

  • The multiple attribute on the file input element.
  • The FileReader object from the new File API.
  • The FormData object from XMLHttpRequest.

We use the multiple attribute to allow the user to select multiple files for upload (multiple file upload will work normally even if FormData isn’t available). As you’ll see, FileReader allows us to show the user thumbnails of the files they’re uploading (we’ll be expecting images).

For older browsers that don't support FormData or FileReader, the upload behavior will fall back to a normal, non-AJAX file upload.

With that out of the way, let’s get coding!

Step 1: The Markup and Styling

Let’s start with some basic markup and styling. Of course, this isn’t the main part of this tutorial, I won’t treat you like a newbie.

The HTML

Pretty basic, eh? We’ve got a form that posts to upload.php, which we’ll look at in a second, and a single input element, of type file. Notice that it has the boolean multiple attribute, which allows the user to select multiple files at once.

That’s really all there is to see here. Let’s move on.

The CSS

No shockers here, we're just creating some basic styling for our upload form.

Step 2: The PHP

We need to be able to handle the file uploads on the back end as well, so let’s cover that next.

upload.php

Bear in mind that these were the first lines of PHP I’d written in easily a year. You should probably be doing a bit more for security; however, we’re simply making sure that there are no upload errors. If that’s the case, we use the built-in move_uploaded_file to move it to an uploads folder. Don’t forget to make sure that the folder is writable.

So, right now, we should have a working upload form. You choose an image (multiple, if you want to and your browser lets you), click the Upload Files! button, and you get the message Successfully Uploaded Images.

Here’s what our mini-project looks like so far:

But, come on, it’s 2020: we want more than that. You’ll notice that we’ve linked up jQuery and an upload.js file. Let’s crack that open now.

Step 3: The JavaScript

Let’s dive right into the JavaScript code for file uploading!

Here’s what we start with. We create two variables: input is our file input element, formdata will be used to send the images to the server if the browser supports that. We initialize it to false and then check to see if the browser supports FormData. If it does, we create a new FormData object. Also, if we can submit the images with AJAX, we don’t need the Upload Images! button, so we can hide it. Why don’t we need it? Well, we’re going to auto-magically upload the images immediately after the user selects them.

The rest of the JavaScript will go inside your anonymous self-invoking function. We next create a little helper function that will show the images once the browser has them:

The function takes one parameter: the image source (we’ll see how we get that soon). Then, we simply find the list in our markup and create a list item and image. We set the image source to the source we received, put the image in the list item, and put the list item in the list. Voila!

Next, we have to actually take the images, display them, and upload them. As we’ve said, we’ll do this when the onchange event is fired on the input element.

So, what do we want to do when the user has selected files? First, we create a few variables. The only important one right now is len = this.files.length. The files that the user has selected will be accessible from the object this.files. Right now, we’re only concerned with the length property, so we can loop over the files... and that is exactly what we’re doing next. Inside our loop, we set the current file to file for ease of access. Next thing we do is confirm that the file is an image. We can do this by comparing the type property with a regular expression. We’re looking for a type that starts with “image” and is followed by anything. (The double-bang in front just converts the result to a boolean.)

So, what do we do if we have an image on our hands?

We check to see if the browser supports creating FileReader objects. If it does, we’ll create one.

Here’s how we use a FileReader object: We’re going to pass our file object to the reader.readAsDataURL method. This creates a data URL for the uploaded image. It doesn’t work the way you might expect, though. The data url isn’t passed back from the function. Instead, the data url will be part of an event object.

With that in mind, we'll need to register a function on the reader.onloadend event. This function takes an event object, by which we get the data URL: it’s at e.target.result. We’re just going to pass this data RUL to our showUploadedItem function (which we wrote above).

Next, we check for the formdata object. Remember, if the browser supports FormDataformdata will be a FormData object; otherwise, it will be false. So, if we have a FormData object, we’re going to call the append method. The purpose of a FormData object is to hold values that you’re submitting via a form; so, the append method simply takes a key and a value. In our case, our key is images[]. By adding the square-brackets to the end, we make sure each time we append another value, we’re actually appending it to that array, instead of overwriting the image property.

We’re almost done. In our for loop, we’ve displayed each of the images for the user and added them to the formdata object. Now, we just need to upload the images. Outside the for loop, here’s the last piece of our puzzle:

Again, we have to make sure we have FormData support; if we don’t, the Upload Files! button will be visible, and that’s how the user will upload the photos. However, if we have FormData support, we’ll take care of uploading via AJAX. We’re using jQuery to handle all the oddities of AJAX across browsers.

You’re probably familiar with jQuery’s $.ajax method: you pass it an options object. The urltype, and success properties should be obvious. The data property is our formdata object. Notice those processData and contentType properties. According to jQuery’s documentation, processData is true by default, and will process and transform the data into a query string. We don’t want to do that, so we set this to false. We’re also setting contentType to false to make sure that data gets to the server as we expect it to.

And that’s it. Now, when the user loads the page, they see this:

And after they select the images, they’ll see this:

And the images have been uploaded:

So that's how you can 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 free library which allows you to implement the file uploads functionality the blink of an eye. It also supports drag-and-drop file uploads along with a beautiful preview feature.

Let's have a look at the following code which implements the file upload functionality with DropzoneJS.

You'll have to download the dropzone.js and dropzone.css files locally first.

Apart from that, you just need to use the dropzone class in the form tag, and the DropzoneJS library will handle the rest!

Let's see how it looks like when you load it in your browser.

As you can see, there's a section which allows you to drop files on it, alternatively you could also select files from your computer by using the default file selection dialog box. Go ahead and drop a few image files on it and it should present you a nice preview as shown in the following screenshot.

Isn't that look amazing with just a few lines of code? In fact, the DropzoneJS library also allows you to customize the UI and other stuff. I would encourage you to check the configuration options provided by this library.

Apart from this, there's the filepond library which is also a popular file upload library you could use. It provides all niche features like drag and drop, progress bar, previews, reordering and alike.

That’s a Wrap!

Uploading files via AJAX is pretty cool, and it’s great that these new technologies support that without the need for lengthy hacks.

Learn JavaScript With a Free Course

If you want to master JavaScript, be sure to check out our free course to learn the complete A-Z of modern JavaScript fundamentals.

 

In this course, you'll learn all of the essential concepts of the JavaScript language. That's right: all of them! Including the most 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 knowledge, from data structures like arrays and maps to loops, control structures, and functions. Along with the basics of the language, you'll also learn some key built-in APIs for manipulating data, AJAX, and working with the web browser DOM. Finally, you'll get a look at some of the most powerful and widely used 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.


What Is Illustration? (And What Are the Different Types of Illustration?)

What Is Illustration? (And What Are the Different Types of Illustration?)
Final product image
What You'll Be Creating

Do you want to know more about illustration? Or do you want to become an illustration artist? Digital illustration, scientific illustration... such a lot of terms! In this article, you'll learn the meaning of illustration, discover illustration types, and much more!

1. What Is Illustration?

Let's dive into an illustration definition. In short, illustration is a visualization made by an artist. It is a drawing (or painting, collage, engraving, photo, etc.) that explains something. The illustration doesn't have to be drawn—a photo in an encyclopedia is also an illustration, because it explains what is written. 

So if your drawing is not explaining something, it is a work of art, not an illustration. We will talk about the differences between art and illustration later.

An illustration can explain an idea even without the text nearby. People who look at the picture should see the story, "read" it as they would read the text. To tell a story with an illustration means to convey some meaning, to explain a certain context only with the help of an image.

The example of an illustration without text
This music festival poster is also an illustration because it illustrates the mood of the festival

Interesting fact: the word illustration comes from the Latin illustrate, which means spiritual or intellectual enlightenment. Wow!

2. Different Types of Illustration

Let's learn more about the types of illustration and where they are used. There are a lot of areas that require visualization; here are some of them:

  • editorial illustration
  • advertising illustration
  • concept art
  • fashion illustration
  • technical (scientific) illustration
  • infographics
  • packaging illustration

What Is Editorial Illustration?

An editorial illustration is an illustration created to better express an idea from the text, usually used in a book, magazine, newspaper, or web resource. This type of illustration can't live without the text. If you want to know more about it, read our tutorial about editorial illustration.

What Is Advertising Illustration?

It is an illustration that is used in promotional material, and its main aim is to catch the viewer's attention. It can be used without any text (only the logotype of the company) but express a strong idea to make it easy to remember.

Advertising illustration example
This e-commerce sale illustration is easy to understand even with very little text

What Is Concept Art?

Concept art is used in movies, games, and other industries, as working material for finding the best image of the atmosphere of the work. Concept art is usually created in several iterations. The most important thing is not to create a perfectly beautiful image, but to choose the appropriate image. The final product uses the final sketch that went through the art director's criticism. Concept art is usually made for environments, characters, costumes, and items.

Characters concept art
Concept Art of cute mascot characters. Different concepts give more choices to use.

What Is Fashion Illustration?

Fashion illustration can be used to visualize a piece of clothing before it’s produced. Fashion designers use it a lot in their creative process. The garment should be drawn before being sewn. Also, fashion houses use fashion illustrators' work to promote their product and to show it in a special style.

Fashion illustration
This trendy girls illustration is a typical fashion illustration

What Is Technical Illustration?

The purpose of a technical (scientific) illustration is to accurately depict an object in order to simplify its understanding. In technical illustration, it is not the image and beauty that is important, but the clarity of the image and the absence of confusion.

Technical scientific illustration
This technical planet illustration shows the structure of the earth's core.

What Are Infographics?

Infographics are a selection of images and diagrams with a minimum of text, allowing you to quickly understand the essence of the topic. Infographics are related to communication and graphic design, but can also be attributed to illustration. Good infographics make it easier to understand information and a large amount of data.

Infographics example
Infographics can be on different topics, like this example of a Covid-19 virus infographic.

What Is Packaging Illustration?

Like advertising illustration, packaging illustration helps companies to sell their product. And it also should be eye-catching and grab the viewer's attention. But also, packaging illustration helps to define the brand, adding a personalized touch and custom feel. 

Packaging illustration
Bright and colorful fruit illustrations are very typical for packaging design.

3. The Difference Between Graphic Design and Illustration

Usually, graphic designers work with ready-made objects, and their task is to create suitable compositions from them. Illustrators create products themselves (even if they are collages).

The main task of the designer is to create a successful product that will meet the requirements of the customer and the needs of the target audience.

A good illustrator will also think about the needs of their client and target audience, but should be more focused on the image itself, rather than on marketing goals—which the designer has already thought about!

Illustrator at work
llustrator at work illustration

4. The Difference Between Art and Illustration

Illustration art is not art in the literal sense of the word. Art is created to express the inner world of the artist, while an illustration is created to explain an idea. The main goal of a work of art is aesthetics. The main purpose of an illustration is to explain. An illustration is created for the needs of a specific customer with specific goals, and a work of art can be made without it. Good illustrators always think about their viewers' and their clients' aims.

5. What Are the Best Illustration Techniques?

It doesn't matter what technique the illustrator uses; what's important is what the illustration is for. This is not a story about how to create an image, but rather about what the purpose of the image is.

A commercial illustration can be traditional in technique: then it is drawn in pencil, ink, and paints. It can be made in digital programs such as Photoshop, Illustrator, Procreate, and others.

Some illustrators use a mixed technique: for example, draw with a pencil, and then process the image on the computer. There are also those who use the collage technique and engraving. You can use any technique; it depends on the purpose of the work and the preferences of the illustrator.

Example of engraving illustration
These vintage engraving horses can be used as a good illustration in an encyclopedia.

6. How to Become a Professional Illustrator

It all depends on the field in which you want to develop, and the technology that you will use. To become an illustrator, it is desirable to be able to draw. But now this is not the main thing, because there are illustration techniques that are not directly related to drawing. But you will definitely need a good knowledge of composition, color, and perspective, and a lot of practice. 

There are a lot of online courses and universities where you can get an education. I advise you to choose courses that focus on the basics of composition and the ability to work with text rather than on individual techniques and materials. Many good tips are collected in our article about editorial illustration.

Knowledge of the basics of marketing, the skill to work with the client, and understanding of legal subtleties will be a good help.

Happy student illustration
Illustration of happy students who just finished their illustration course!

Conclusion

Illustration is a very interesting area that simultaneously contains a lot of creativity and close work with the client and designers. But the pleasure when you see your work printed in a magazine or on a shelf in a store cannot be compared to anything!

I wish you good luck and patience on this difficult but very exciting journey.

Want to learn more about illustration and graphic design? Check out our other tutorials and articles! I'm absolutely sure that you will find the perfect tutorial for improving your skills.


How to Use Tone Curves to Correct and Adjust Photos in Adobe Camera RAW (Free)

How to Use Tone Curves to Correct and Adjust Photos in Adobe Camera RAW (Free)

Curves tools can be really useful for your editing process, giving you greater speed and control over exposure, contrast and even colour, over the dynamic tonal range of your image. Here we'll take a look at the Curves tools in Adobe Camera Raw.

What is a Tone Curve?

Tone curves represent the range of tones and changes between them in your picture.

‘The horizontal axis represents the original tone values of the image (input values), with black on the left and progressively lighter values toward the right. The vertical axis represents the changed tone values (output values), with black on the bottom and progressing to white at the top.’  Source: Adobe

You'll usually use the Curve options to adjust contrast and exposure, though you can do more than that by also adjusting specific colour channels within the Curves tools too.

How to use Tone Curve in Camera Raw

You’ll have noticed that in the more recent updates to ACR, the Tone Curve section has changed a little. If you’re following along and have an older version of the software, it might be worth you updating – you can do this for free if you have either a current CC subscription, or have an active older version of linked Adobe software like Photoshop or Lightroom.

Make Basic Adjustments First

You should use the Tone Curve adjustments once you’ve already made your Basic adjustments, using the tone curve to fine tune rather than make massive changes.

image with basic adjustments
Image with basic adjustments

This is the image I’ll work with to demonstrate. I’ve made a few basic adjustments like dropping the highlights to bring back some of the blue sky, brightening the shadows and adding a little contrast and texture.

Tone Curve

Parametric Curve and Point Curve

parametric and point curve
Parametric and Point Curve

If you’ve used curves in the past, you’ve probably been used to Point Curve. Parametric Curve can be used in addition to point, changing one won’t alter the other.

Parametric Curve

Parametric Curve splits your tones into sections: highlights, lights, darks and shadows, and you’ll see you have sliders that you can adjust that reflect those. Unlike Point Curve which I’ll go into shortly, Parametric Curve will limit your dragging of points to that group of tones and won’t let you go beyond that.

Although just to throw some confusion into the mix, you do have a strip above the sliders with three points on. Moving these points will increase the range of the tones. For example, if you shifted all the dots to the right (towards highlights) then making changes to the ‘shadows’ slider would have an increased effect, as it would now take ‘shadows’ to mean you want to include all the tones up to that first dot!

dots and sliders
Dots and sliders

The good thing about Parametric Curve is that it makes it more obvious (than Point Curve) which tones you’re affecting. If you hover over the graph to make changes, rather than via the sliders, it’ll tell you when you move from shadows (your darkest tones) to darks.

showing tonal region
Parametric Curve tonal region

Making and dragging a point on the graph will only let you make vertical changes, so an increase or decrease in the point you’ve selected and that will then be reflected on the corresponding slider. It’s easier to make changes to Parametric Curve with the sliders.

If you aren’t familiar with curves, Parametric Curve will be the easiest option to use and it will help prevent you from making any crazy adjustments that will make your image look odd.

Point Curve

Point Curve will still give you the most control because you have more freedom to create extra control points and make more targeted adjustments to the tones in your image.

Point Curve has some standard options to choose from: Medium Contrast and Strong Contrast.

point curve set to strong contrast
Point Curve set to Strong Contrast

Above, Strong Contrast is selected, which you can see puts the line on the graph into a gentle ‘S’ curve, meaning the shadows are deepened, the lights are lifted and the midtones stay much the same.

If I exaggerate that ‘S’ (below) you can see the image would be very high in contrast, to the point where tones at both ends of the graph are lost and everything looks a bit over the top and unrealistic.

exaggerated s curve
Exaggerated 's' curve

If you like a matte effect on your shadows, you can leave the ‘S’ curve in place and then lift the furthest left control point (the shadows) up to create a slight ‘U’ shape.

matte effect
Using curves to create a matte effect

Red Channel, Green Channel and Blue Channel

red blue green channel
Red, Blue, Green Channels

This set of options also don’t change anything you may have done to parametric and point curve. They work in a similar way to the previous curve descriptions, only this time they focus on just one set of colour values.

making everything blue
Making everything blue...

If we take the blue channel as an example, making a control point in the middle and dragging it up would make the midtones bluer, as seen in the image above. If I dragged it down, it would make them more yellow.

You can use these to apply more thoughtful colours to specific tones. For example you might want to add some cooler tones to your shadows, which might look like this.

adding blues to shadows
Adding blues to shadows

Each colour channel will have its opposite on the colour wheel as a negative value. So for example the red channel has cyan, so a lift in control points would increase red and decrease cyan – pulling that point down instead would do the opposite, increase cyan and decrease red within that tonal range.

Finishing Up

before and after
Before (left) and After (right) curve adjustments

Curves are great ways to make smaller adjustments to your images – changes that affect the exposure, contrast and colours. Be wary of doing too much in curves though, you can quite quickly pull control points beyond the reasonable limits of your photographs and end up with something that just looks a little odd!

When used properly, curves can give you more targeted adjustments to specific tonal regions that other editing panels can’t, which gives you greater control over your whole dynamic range. If you’re new to curves, I’d recommend starting with Parametric Curves which will keep you within the limits of your available tonal range. It’s also easier to adjust because of the sliders. It’s worth playing around with the Point Curve and Colour Channel tools though, to see what results you get and to learn which adjustments will work for your image.

Finally, if you're still using an older version of Adobe Camera Raw the Curves tool will look a little different, and you might find this video useful:

More Help With Adobe Camera Raw