Computer scienceProgramming languagesJavaScriptInteraction with a browserDOM Interaction

Uploading files and images

10 minutes read

Most websites allow users to upload various files and images. You can upload videos, photos, and files of different formats to social networks. On sites where authentication is required, you can upload your profile photo. Let's look at how you can do this.

Uploading files and images

You can upload files using a form and a special <input> tag. The <input> tag is an HTML element for receiving data from users.

The syntax of the <input> tag goes like this:

<input attributes>

Here are its main attributes:

  • type — the type of the displayed HTML element. There are such types as text input fields, password input fields, buttons, checkboxes, radio buttons, and file selection buttons.

  • accept used to specify the type of file you want to upload. This attribute can only be used with the <input type="file"> element.

  • multiple — select multiple values to send to the server.

  • enctype used to determine how to encode form data to be sent to the server. Note that this attribute is allowed to be used only if the value of the method attribute has "POST" as the value. Here is how form data can be encoded:

enctype="application/x-www-form-urlencoded | multipart/form-data | text/plain"

  • application/x-www-form-urlencoded — all characters are encoded before sending (plus sign "+" is inserted instead of spaces, and characters are encoded by their ASCII hexadecimal values). This is the default value.

  • multipart/form-data — data is not encoded. This value is applied when sending files.

  • text/plain — spaces are replaced with the plus sign "+", letters and symbols are not encoded.

Let's look at some examples of how to download files.

Simple upload

To upload a file, you need to add the input field type "file" to the <input> tag, in which files are used as values:

<h2>File and image upload</h2>
<form method="POST" enctype="multipart/form-data">
 <div>
   <input type="file" id="file" multiple>
 </div>
</form>

The result looks like this:

Rendered HTML fieldset with browse button that allows to select files to upload and the label - File and image upload

The output of file contents

Before uploading a file or image to the server, you need to find out what's in it. To do that, we'll display the content on the screen.

Note that these examples don't consider sending data to the server.

To do this, we will slightly change the structure and connect JavaScript.

1) In the HTML document, add <div id="content"></div>. Here we will add the content.

2) Get the file uploader by ID:

const fileUploader = document.getElementById('file');

3) The FileReader object lets web applications asynchronously read the contents of files stored on the user's computer.

const reader = new FileReader();
const content = document.getElementById('content');

4) Add a handler for the change event.

The change event occurs at the end of changing the form element's value when this change is fixed. For text elements, this means that the event will occur not every time you type, but when you lose focus.

fileUploader.addEventListener('change', (event) => {
  // The target event property returns the element that triggered the event. 
  const files = event.target.files;

  // Get the file object and read the data as URL binary string
  reader.readAsDataURL(files[0]);
  
  reader.addEventListener('load', (event) => {
    // Create an image tag and fill it
    const img = document.createElement('img');
    img.classList.add('content')
    content.appendChild(img);
    img.src = event.target.result;
  });
});

The load event means that the browser has loaded HTML and external resources (images, styles, etc.).

5) This is result that will be output:

Violet html page with File and image upload tittle, browse button to select files, submit button, and image as a result of selected image

Drag and drop

The previous examples look may a bit too simplistic and boring, and on most modern sites you can add files by dragging and dropping. Let's see how this can be implemented.

1) Let's create two sections, the first for drag and drop, and the second for display.

<!-- drag and drop section -->
<div id="section-drop">
  <p class="text">Drag and Drop files here</p>
</div>
<!-- section to display -->
<div id="aside"></div>

2) Get the drag areas and content by their respective IDs.

const sectionDrop = document.getElementById('section-drop');
const aside = document.getElementById('aside');

3) Next, we define what we want to do when the image is deleted. To do this, we need to add a handler for the drop event.

4) The dragover event is triggered on the target element when the mouse pointer with the draggable element is above it. The handler of this event should set the dataTransfer.dropEffect property to specify the action to be performed at the end of the drag: copy, link creation, or move.

sectionDrop.addEventListener('dragover', event => {
    event.stopPropagation();
    event.preventDefault();
    event.dataTransfer.dropEffect = 'copy';
  });

sectionDrop.addEventListener('drop', event => {
  aside.innerHTML = '';
  event.stopPropagation();
  event.preventDefault();
  const files = event.dataTransfer.files;

  reader.readAsDataURL(files[0]);

  reader.addEventListener('load', (event) => {
    aside.innerHTML = '';
    const img = document.createElement('img');
    img.style.height = '50%';
    img.style.width = '50%';
    aside.appendChild(img);
    img.src = event.target.result;
    sectionDrop.style.display = 'none'
  });
});

The drop event occurs when we release an element, provided that the dragover event is always canceled by the preventDefault() method.

Try dragging the object and see how it works.

Conclusion

Uploading files and images is a common task for users. You can upload files and images using the <input> tag and JavaScript. Thanks to JavaScript, you are able to not only upload data, but also manage the contents of the file, find out the file size, show the file download process, and so on.

20 learners liked this piece of theory. 8 didn't like it. What about you?
Report a typo