Key takeaways
- An AJAX file upload posts the file in a background HTTP request, so the page the user is looking at never reloads.
- Three pieces do the work: a FormData object holding the file, XMLHttpRequest or fetch to send it, and a server endpoint that reads the multipart request.
- Upload progress events fire on xhr.upload, and the listeners have to be attached before open() is called. fetch has no upload progress event at all.
- Never trust the filename, the extension or the type field the browser sends. Verify the type from the bytes on the server, and store the file under a name you generate.
- Posting straight from the browser to Cloudinary removes the storage, validation and delivery work from your own server, and the file never passes through it.
AJAX file upload is the process of uploading files from a local computer to a server. When a user selects a file in the browser and clicks the submit button, the browser copies the file from the local machine and sends it to the server. The server then saves the file to the specified location.
In this article, you’ll find:
- How to perform a PHP AJAX file upload
- A useful JavaScript AJAX file upload example
- An AJAX file upload example using Cloudinary for free
- How to add an upload progress bar, a cancel button and multiple-file support
- How XMLHttpRequest, fetch and jQuery $.ajax compare for uploads
- How Cloudinary compares with Uppy, Dropzone.js, Filestack and Uploadcare
The HTML form tag has an action attribute pointing to the script that will take care of the actual upload process. The form tag also has a method attribute that specifies the kind of operation this form will undertake, which is POST. AJAX uses the browser’s built-in XMLHttpRequest object to request data from the web server. It also uses JS and HTML DOM to use and display the data.
Web apps built using AJAX are efficient because they can quickly send and fetch data from the server without affecting the display of the existing page. Files can be uploaded to a backend server or directly to the cloud using a solution like Cloudinary.
There are the general steps for uploading a file using AJAX:
- Set up an instance for XMLHttpRequest.
- Set up objects for various XMLHttpRequest handlers.
- Set an AJAX request to send data to the back end.
- Validate the form.
- Provide feedback to the user.
To make this process easier, you can use Cloudinary, a cloud-based, end-to-end media-management solution that can easily create, manage and deliver their digital experiences across any browser, device and bandwidth. Make sure you try this yourself, claim your free Cloudinary account now.
This article describes how easy it is to do an AJAX file upload with Cloudinary using only a few lines of code and no need for any of the above tasks.
An AJAX (Asynchronous JavaScript and XML) file upload is a file transfer made with a background HTTP request instead of a form submission. A plain form with a file input navigates the browser to the server’s response, which throws away the page the user was on. An AJAX upload intercepts the submit event, builds the request in JavaScript and sends it, so the user keeps their scroll position, their other form fields and any state the app holds in memory.
Three pieces do the work:
- FormData builds a multipart/form-data request body from the File object, and sets the Content-Type header with the correct boundary string.
- XMLHttpRequest or fetch sends that body to a URL you choose, asynchronously.
- Your server receives the request exactly as it would receive a native form post, reads the file, validates it and stores it.
Nothing about the file itself changes. What changes is who controls the page after the bytes leave: with an AJAX upload, your JavaScript does.
The markup needs a file input, a submit button and somewhere to report status. It does not need an action attribute, because the submit event is intercepted before the browser would use it.
<form id="upload-form">
<label for="file">Choose a file</label>
<input type="file" id="file" name="file" accept="image/png,image/jpeg,image/webp" required>
<button type="submit">Upload</button>
</form>
<p id="status" role="status" aria-live="polite"></p>
<script src="upload.js"></script>
Code language: HTML, XML ( xml )
upload.js holds the whole client side:
const form = document.querySelector('#upload-form');
const input = document.querySelector('#file');
const statusEl = document.querySelector('#status');
form.addEventListener('submit', (event) => {
event.preventDefault();
const file = input.files[0];
if (!file) {
statusEl.textContent = 'Choose a file first.';
return;
}
const body = new FormData();
body.append('file', file, file.name);
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {
statusEl.textContent = xhr.status === 200
? 'Upload complete.'
: 'The server rejected the upload (HTTP ' + xhr.status + ').';
});
xhr.addEventListener('error', () => {
statusEl.textContent = 'Network error. Check the connection and try again.';
});
xhr.open('POST', '/fileUpload.php');
xhr.send(body);
statusEl.textContent = 'Uploading...';
});
That is a working AJAX file upload, with no library and no account. Point it at any endpoint that reads a multipart/form-data field named file.
Two things in it are easy to get wrong:
- load fires when the response arrives, including on a 4xx or 5xx, so check xhr.status yourself rather than treating load as success.
- Don’t set Content-Type by hand. Setting it overwrites the multipart boundary that FormData generated, and the server then parses an empty request.
As a first step, create a free Cloudinary account, which includes a dashboard, a unique cloud name for you, an API key, and an API secret, which you’ll need to work with Cloudinary.
Subsequently, create an upload preset, which defines the options that apply to all your uploads.
For a browser upload, set the preset’s signing mode to unsigned. Cloudinary’s upload documentation states that unsigned uploads require an unsigned upload preset, and that for security reasons only a small set of upload parameters can be passed directly in an unsigned upload call, so everything else has to be configured on the preset.
That means the preset where the restrictions live: set allowed_formats and a maximum file size there, and keep the format list narrow. Treat the preset name as sensitive, because an unsigned preset accepts uploads from anyone who knows it.
Follow these simple steps:
Create an HTML form.
In your root directory, create an HTML form (an index.html file) with the following code, which contains the fields for file uploads:
index.html
<!DOCTYPE html >
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title > AJAX File Uploads With Cloudinary </ title >
</ head >
< body >
< form id = "file-form" action = "fileUpload.php" method = "post" enctype = "multipart/form-data" >
Upload a File:
< input type = "file" id = "myfile" name = "myfile" >
< input type = "submit" id = "submit" name = "submit" value = "Upload File Now" >
</ form >
< p id = "status" > </ p >
< script type = "text/javascript" src = "fileUpload.js" > </ script >
</ body >
</ html >
You now have a form with the following elements:
- An input field and a submit button.
- An action attribute—within the form tag—that points to the script that handles the upload.
- A method attribute that specifies the operation post undertaken by this form.
- An enctype attribute, whose value specifies the content type of the upload. multipart/form-data is the value a native form submit needs in order to send file bytes. It’s used only on a native submit: once the submit event is intercepted and a FormData object is sent instead, the browser sets the Content-Type and the multipart boundary on the request itself, and the attribute is ignored.
- An id attribute for both input fields, which handle the form elements with JavaScript.
Add the Cloudinary JavaScript library.
JavaScript plugins on Cloudinary facilitate image uploads to its server. Include them in your index.html file, like this:
<script src="https://upload-widget.cloudinary.com/latest/global/all.js" type="text/javascript"></script>
The latest path picks up current fixes on its own, and the documentation also shows a version-pinned path if you would rather control when the widget changes.
const widget = cloudinary.createUploadWidget(
{
cloudName: 'YOUR_CLOUD_NAME',
uploadPreset: 'YOUR_UPLOAD_PRESET',
},
(error, result) => {
if (error) {
console.error(error);
return;
}
if (result && result.event === 'success') {
document.querySelector('#preview').src = result.info.secure_url;
}
}
);
document.querySelector('#open-widget').addEventListener('click', () => widget.open());
Add <button type="button" id="open-widget">Upload</button> and <img id="preview" alt=""> to the page for the widget to open from and write its result into. The widget gives you the file picker, drag and drop, previews, its own progress display and retries, in one script tag.
The callback receives one result object and fires for several events, which is why the handler checks result.event === 'success' before reading result.info.
Be sure to replace the YOUR_CLOUD_NAME and YOUR_UPLOAD_PRESET variables with their values from your Cloudinary dashboard. The API key and the API secret stay out of browser code: an unsigned upload needs only the cloud and preset names.
The widget draws its own interface. When the progress has to appear inside your own design instead, post to the Upload API with XMLHttpRequest and keep your own progress bar. The endpoint format for Cloudinary is
https://api.cloudinary.com/v1_1/<cloud name>/<resource_type>/upload
So for images it will look like:
https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload
The body is the same FormData object from the first example, plus the preset name.
const CLOUD_NAME = 'YOUR_CLOUD_NAME';
const UPLOAD_PRESET = 'YOUR_UPLOAD_PRESET';
function uploadToCloudinary(file, onProgress) {
return new Promise((resolve, reject) => {
const body = new FormData();
body.append('file', file);
body.append('upload_preset', UPLOAD_PRESET);
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
onProgress(Math.round((event.loaded / event.total) * 100));
}
});
xhr.addEventListener('load', () => {
let payload;
try {
payload = JSON.parse(xhr.responseText);
} catch (e) {
reject(new Error('The response was not JSON.'));
return;
}
if (xhr.status === 200) {
resolve(payload);
} else {
reject(new Error('Upload failed with HTTP ' + xhr.status));
}
});
xhr.addEventListener('error', () => reject(new Error('Network error.')));
xhr.open('POST', 'https://api.cloudinary.com/v1_1/' + CLOUD_NAME + '/image/upload');
xhr.send(body);
});
}
The response carries secure_url for display and public_id, which is the identifier to store in your own database. Use auto in place of image in the endpoint to let Cloudinary detect the resource type rather than assuming an image.
| Unsigned | Signed | |
| What the browser sends | The file and upload_preset | The file, api_key, timestamp and signature |
| Where the API secret lives | Nowhere in the request | Your server only |
| Who can upload | Anyone who learns the preset name | Only callers your server issued a signature to |
| Where the options are set | On the preset | In the signed request, or on the preset |
| Extra moving part | None | An endpoint on your server that returns a signature |
Use unsigned uploads when the preset’s own restrictions are enough. Use signed uploads when the upload has to be tied to an authenticated user, or rate-limited.
Where an upload lands is the part a security review asks about, so these are the specifics worth having to hand.
- Uploads post over HTTPS to api.cloudinary.com, and the widget and the Upload API use the same endpoint.
- After the upload, delivery can be restricted instead of left open. Adding the sign_url parameter produces a signed delivery URL, which is what authorizes access to private and authenticated assets. The same documentation is explicit about the limit of that control: a signed URL does not prevent link sharing.
- Uploading with the authenticated delivery type means the original file and any derived versions are accessible only through a signed URL, and on-the-fly transformations cannot be created for those assets.
- Strict transformations block transformation URLs that were not explicitly allowed. Once it is switched on, transformations can only be created through eager transformations, signed delivery URLs, allowed named transformations or allowed referral domains.
For access that has to expire, token-based authentication adds a signed token through auth_token alongside sign_url. It takes either duration, the number of seconds the URL stays valid, or expiration, a UNIX timestamp. At least one of the two is required, and duration is ignored if both are given. The token’s encryption key is not your API secret.
To handle file uploads with AJAX and store the files on a backend server (e,g PHP Server), create an HTML form and two upload scripts: one written in JavaScript and the other in PHP.
In your root directory, build an HTML form (an index.html file) with the following code, which contains the fields for file uploads:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Uploads With AJAX</title>
</head>
<body>
<form id="file-form" action="fileUpload.php" method="post" enctype="multipart/form-data">
Upload a File:
<input type="file" id="myfile" name="myfile">
<input type="submit" id="submit" name="submit" value="Upload File Now">
</form>
<p id="status"></p>
<script type="text/javascript" src="fileUpload.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
Note the following:
- The form contains an input field and a submit button.
- The form tag has an action attribute that points to the script that will take care of the actual upload process. It also has a method attribute that specifies the kind of operation this form will undertake, which is post.
- An enctype attribute, whose value specifies the content type of the upload. multipart/form-data is the value a native form submit needs in order to send file bytes. It is used only on a native submit: once the submit event is intercepted and a FormData object is sent instead, the browser sets the Content-Type and the multipart boundary on the request itself, and the attribute is ignored.
- An id attribute for both input fields, which handles the form elements with JavaScript.
JavaScript AJAX File Upload Example
In your root directory, create a file called fileUpload.js with the following code:
( function ( ) {
var form = document .getElementById( 'file-form' );
var fileSelect = document .getElementById( 'myfile' );
var uploadButton = document .getElementById( 'submit' );
var statusDiv = document .getElementById( 'status' );
form.onsubmit = function ( event ) {
event.preventDefault();
statusDiv.innerHTML = 'Uploading . . . ' ;
// Get the files from the input
var files = fileSelect.files;
// Create a FormData object.
var formData = new FormData();
//Grab only one file since this script disallows multiple file uploads.
var file = files[ 0 ];
//Check the file type.
if (!file.type.match( 'image.*' )) {
statusDiv.innerHTML = 'You cannot upload this file because it's not an image.' ;
return ;
}
if (file.size >= 2000000 ) {
statusDiv.innerHTML = 'You cannot upload this file because its size exceeds the maximum limit of 2 MB.' ;
return ;
}
// Add the file to the AJAX request.
formData.append( 'myfile' , file, file.name);
// Set up the request.
var xhr = new XMLHttpRequest();
// Open the connection.
xhr.open( 'POST' , '/fileUpload.php' , true );
// Set up a handler for when the task for the request is complete.
xhr.onload = function ( ) {
if (xhr.status === 200 ) {
statusDiv.innerHTML = 'Your upload is successful..' ;
} else {
statusDiv.innerHTML = 'An error occurred during the upload. Try again.' ;
}
};
// Send the data.
xhr.send(formData);
}
})();
Step by step, the process proceeds as follows:
Grab all the elements, i.e., the form, the file-input, and status div, as reflected in this code:
var form = document .getElementById( 'file-form' );
var fileSelect = document .getElementById( 'myfile' );
var statusDiv = document .getElementById( 'status' );
Call the form’s onsubmit event. After the user has submitted the form, attach an event handler to the form:
form.onsubmit = function ( event ) {
….
}
Get hold of the file specified by the user and, for a robust experience, keep that user informed of what’s transpiring behind the scenes, like this:
...
statusDiv.innerHTML = 'Uploading . . . ' ;
// Picking up files from the input . . .
var files = fileSelect.files;
// Uploading only one file; multiple uploads are not allowed.
var file = files[ 0 ];
...
Create a form object, validate the size and type of the file to be uploaded, and add the file to form, like this:
// Create a FormData object.
var formData = new FormData();
// Check the file type.
if (!file.type.match('image.*')) {
statusDiv.innerHTML = 'You cannot upload this file because it’s not an image.';
return;
}
if (file.size >= 2000000) {
statusDiv.innerHTML = 'You cannot upload this file because its size exceeds the maximum limit of 2 MB.';
return;
}
// Add the file to the request.
formData.append('myfile', file, file.name);
Code language: JavaScript (javascript)
Set up an AJAX request, open a connection, and listen for the onload event of the xhr object.
// Set up an AJAX request.
var xhr = new XMLHttpRequest();
// Open the connection.
xhr.open( 'POST' , '/fileUpload.php' , true );
// Set up a handler for when the task for the request is complete.
xhr.onload = function () {
if (xhr.status === 200 ) {
statusDiv.innerHTML = 'Your upload is successful. ';
} else {
statusDiv.innerHTML = 'An error occurred while uploading the file... Try again';
}
};
// Send the Data.
xhr.send(formData);
Here, you make a post request to fileUpload.php. And yes, you must still process the file on the back end, to which the AJAX request submits the file for processing.
Before leveraging the preceding code for production, you must make provisions for several edge cases, for example, perform checks to ensure that only safe files are posted to your back end.
PHP script
Below is the script written in PHP.
<?php
$currentDir = getcwd();
$uploadDirectory = "/uploads/";
$errors = []; // Store all foreseen and unforeseen errors here.
$fileExtensions = ['jpeg', 'jpg', 'png']; // Allowed file extensions.
$fileName = $_FILES['myfile']['name'];
$fileSize = $_FILES['myfile']['size'];
$fileTmpName = $_FILES['myfile']['tmp_name'];
$fileType = $_FILES['myfile']['type'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($fileName)) {
if (!in_array($fileExtension, $fileExtensions)) {
$errors[] = "This process does not support this file type. Upload a JPEG or PNG file only.";
}
if ($fileSize > 2000000) {
$errors[] = "You cannot upload this file because its size exceeds the maximum limit of 2 MB.";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo "The file " . basename($fileName) . " has been uploaded.";
} else {
echo "An error occurred. Try again or contact your system administrator.";
}
} else {
foreach ($errors as $error) {
echo $error . "\n";
}
}
}
?>
Code language: HTML, XML (xml)
Ensure you are running a PHP server:
Now when you run that PHP app, it looks like this:
In addition, note the following:
- The PHP script works for image files only.
- The file-size limit is 2 MB.
Upload images to a dedicated file server in addition to the server in which your web app resides. Check out this source code for a related tutorial.
Progress events for an upload fire on xhr.upload, not on the request object itself. MDN’s guide to using XMLHttpRequest is explicit that the listeners have to be added before open() is called, or the progress events do not fire.
Add a progress element to the form:
<progress id="bar" value="0" max="100" hidden></progress>
Code language: HTML, XML (xml)
Then attach the listener while the request is still being configured, before open():
const bar = document.querySelector('#bar');
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (event) => {
if (!event.lengthComputable) {
// The total size is unknown, so no percentage can be calculated.
statusDiv.innerHTML = 'Uploading...';
return;
}
const percent = Math.round((event.loaded / event.total) * 100);
bar.hidden = false;
bar.value = percent;
statusDiv.innerHTML = percent + '% uploaded';
});
xhr.open('POST', '/fileUpload.php');
xhr.send(formData);
event.loaded is the number of bytes sent so far and event.total the number to send. When lengthComputable is false, the total length is not known and is reported as zero, so check it before dividing.
A large upload needs a way out. xhr.abort() cancels the request in flight, and the abort event on xhr.upload is where the interface resets. Add a <button type="button" id="cancel">Cancel</button> next to the submit button for it to hang off.
// csrfToken comes from your page, for example a meta tag your template renders.
let current = null;
function upload(file) {
const formData = new FormData();
formData.append('myfile', file, file.name);
const xhr = new XMLHttpRequest();
current = xhr;
xhr.upload.addEventListener('abort', () => {
statusDiv.innerHTML = 'Upload canceled.';
});
xhr.upload.addEventListener('error', () => {
statusDiv.innerHTML = 'The transfer failed before it completed.';
});
xhr.addEventListener('timeout', () => {
statusDiv.innerHTML = 'The upload timed out.';
});
xhr.addEventListener('load', () => {
current = null;
});
xhr.open('POST', '/fileUpload.php');
xhr.timeout = 120000;
xhr.setRequestHeader('X-CSRF-Token', csrfToken);
xhr.send(formData);
}
document.querySelector('#cancel').addEventListener('click', () => {
if (current) current.abort();
});
Three ordering rules apply here, and breaking any of them can lead to an issue without throwing an error:
- upload progress listeners go on before open()
- setRequestHeader() works only after open() and before send()
- xhr.timeout has to be set before send().
A custom header such as X-CSRF-Token is also what turns a cross-origin upload into a preflighted request, so the endpoint’s OPTIONS response has to allow that header.
The script above handles one file on purpose. To accept several, add multiple to the input and append each file under the same field name with a [] suffix, which is what makes PHP parse it as an array.
<input type="file" id="files" name="files[]" multiple>
Code language: HTML, XML ( xml )
const formData = new FormData();
for (const file of document.querySelector('#files').files) {
formData.append('files[]', file, file.name);
}
On the PHP side, $_FILES[‘files’] then holds parallel arrays, so $_FILES[‘files’][‘tmp_name’][0], [‘tmp_name’][1] and so on, with a matching [‘error’] entry per file.
The accept attribute and the file.type.match() check above are interface conveniences. They tell the user what is wanted before they wait for an upload. They prove nothing, because a request built with curl never runs your JavaScript. Four holes close on the server:
-
The extension is user input. Taking the extension from
$_FILES['myfile']['name']lets a caller name a scriptavatar.pngoravatar.php.png. Derive the extension from a type you verified instead. -
The type field is user input too.
$_FILES['myfile']['type']is copied from the request’s own part header. Read the type from the bytes on disk with the bundled fileinfo extension instead:(new finfo(FILEINFO_MIME_TYPE))->file($fileTmpName). - A verified image can still carry a payload. Type sniffing tells you the first bytes look like a JPEG, not that the rest is harmless. The control that works is storing the file where the web server will never execute it, which means a directory outside the document root rather than an /uploads/ folder under it.
-
The client filename can collide.
basename()handles path traversal, but two users uploading photo.jpg still overwrite each other. Generate the stored name yourself, for example withbin2hex(random_bytes(16)), and keep the original name in your database if you need to show it.
Check $_FILES['myfile']['error'] against UPLOAD_ERR_OK and call is_uploaded_file() before move_uploaded_file(). If you accept file types other than images, add a malware scan in front of storage, because neither PHP nor a type check is sufficient.
These are PHP’s documented defaults, from the core configuration list in the manual. The third row is the one that produces the confusing bug report, because $_FILES arrives empty with no error code to inspect.
| Directive | Default | What happens when it is exceeded |
| file_uploads | 1 | Uploads are disabled entirely when it is switched off. |
| upload_max_filesize | 2M | The file appears in $_FILES with error set to UPLOAD_ERR_INI_SIZE. |
| post_max_size | 8M | $_POST and $_FILES are both empty. There is no per-file error code. |
| max_file_uploads | 20 | Files past the limit are not present in $_FILES at all. |
Keep post_max_size above upload_max_filesize, because the request body also carries the multipart headers and any other form fields. Your web server has its own ceiling as well, such as nginx’s client_max_body_size, and the lowest of the three wins.
All three send the same multipart/form-data request. They differ in what they let you observe while it is in flight.
| Approach | Upload progress | Cancel | Dependency | Use it when |
| XMLHttpRequest and FormData | Yes, through progress events on xhr.upload | xhr.abort() | None | You need a progress bar. This is still the way to get one. |
| fetch and FormData | No upload progress event | AbortController | None | The upload is small enough that a spinner is honest, and you want promises. |
| jQuery $.ajax and FormData | Yes, by returning your own XHR from the xhr option | abort() on the returned jqXHR | jQuery | jQuery is already on the page and you do not want two request styles in one codebase. |
| Hosted uploader or widget | Built in | Built in | A script tag or a package | You want the picker, retries and validation handled, and you accept a vendor in the upload path. |
The fetch version is the shortest:
async function upload(file) {
const formData = new FormData();
formData.append('myfile', file, file.name);
const response = await fetch('/fileUpload.php', { method: 'POST', body: formData });
if (!response.ok) {
throw new Error('Upload failed with HTTP ' + response.status);
}
return response.json();
}
fetch resolves as soon as the response headers arrive and exposes no event for bytes sent, which is why a progress bar built on fetch can only guess. For a real percentage, use XMLHttpRequest for the upload and keep fetch for everything else.
The jQuery version needs two settings that are easy to miss:
$('#file-form').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: '/fileUpload.php',
type: 'POST',
data: new FormData(this),
processData: false, // Do not let jQuery serialize FormData into a string.
contentType: false, // Let the browser set multipart/form-data and the boundary.
xhr: function () {
const xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', onProgress);
return xhr;
}
});
});
In this code:
- processData: false stops jQuery turning the FormData object into a query string, which drops the file contents.
- contentType: false stops it setting a Content-Type without a boundary.
- new FormData(this) picks up the file input on its own, because the input has a name attribute.
The comparison that matters is not library against service. It is how much of the upload path you want to own.
| Tool | What it is | Progress interface | Server code you still write |
| XMLHttpRequest and FormData | No dependency, about 25 lines | You build it | Endpoint, validation, storage, resizing, delivery |
| Dropzone.js | Open-source drag-and-drop upload component for the browser | Included | Everything on the server |
| Uppy | Open-source JavaScript file uploader for the browser | Included | Everything on the server |
| Filestack | Hosted file upload and delivery service with a picker | Included | None for the upload itself |
| Uploadcare | Hosted file upload, storage and delivery service | Included | None for the upload itself |
| Cloudinary Upload API or upload widget | Hosted upload, plus image and video transformation and CDN delivery | Included in the widget, or build your own against the Upload API | None for the upload itself |
Dropzone.js and Uppy replace the picker and the progress interface, and the server work does not go away. Filestack, Uploadcare and Cloudinary replace the server work, and the difference between them is what happens to the file afterward. Cloudinary’s answer is transformation and delivery of images and video.
- It doesn’t scan files for viruses. The moderation add-ons judge image and video content, which is not an antivirus pass over arbitrary file types.
- It doesn’t authenticate users. An unsigned preset is open to anyone who learns the name, so abuse control means a signed flow, or your own endpoint in front of it.
- It doesn’t keep the data on your own infrastructure. If a requirement says the file must never leave hardware you control, the PHP handler above is the right answer, not a hosted service like Cloudinary.
- The widget doesn’t expose its progress to your own interface. When the percentage has to appear inside your design, post to the Upload API with XMLHttpRequest instead.
- It’s built around media. Arbitrary files can be stored as raw resources, but the transformation and optimization features apply to images and video.
The decision underneath all of this is simple. An AJAX file upload is a FormData object and about 25 lines of JavaScript, and the work is in what surrounds it: a progress bar that reports the transfer rather than the outcome, a cancel path, and a server that treats every field the browser sent as untrusted. Write that handler when the file has to stay on infrastructure you control. When it does not, posting straight to the Upload API with XMLHttpRequest keeps your own progress bar and removes the storage, validation and delivery work.
Uploading AJAX files with Cloudinary is a cakewalk. Even though mastering AJAX technologies could be challenging, you can take advantage of them readily with the Cloudinary library for your app. Give it a try: signing up for Cloudinary is free.
- Automating File Upload and Sharing
- Uploading PHP Files and Rich Media the Easy Way
- Impressed by WhatsApp technology? Clone WhatsApp Technology to Build a File Upload Android App
- Direct Image Uploads From the Browser to the Cloud With jQuery
- File Upload With Angular to Cloudinary
- Uploading Vue Files and Rich Media in Two Easy Steps
- Node.js File Upload To a Local Server Or to the Cloud
- Laravel File Upload to a Local Server Or to the Cloud
- JavaScript File Upload in Two Simple Steps