$ npm install filestack-jsconst client = filestack.init('YOUR_API_KEY');
client.picker({
onUploadDone: (res) => console.log(res.filesUploaded),
}).open();
"filename": "myfile.png",
"handle": "AFrHW1QRsWxmu5ZLU2qg",
"url": "https:/
"status": "Stored"
}
JavaScript File Upload at a Glance
JavaScript file upload sends a file from the browser to a server, usually with FormData and fetch or XMLHttpRequest. Production uploads add progress, validation, retries and storage. Filestack’s JavaScript SDK (filestack-js) delivers all four: a drop-in picker with drag and drop and cloud sources, resumable uploads, and managed storage, in a few lines of code.
fetch and FormData
- FormData Wraps the chosen file
- Your endpoint Parses the multipart body
- Your storage Keeps the file
filestack-js
- Picker or upload() Device, camera or cloud
- Filestack Uploads in resumable parts
- Handle and URL Returned to your callback
- Package
filestack-json npm, or one script tag from the Filestack CDN- Framework SDKs
- React and Angular, plus guides for Vue 3, SvelteKit, Astro and SolidStart
- Sources
- Device, camera, URL, Google Drive, Dropbox, OneDrive, Box and more
- Large files
- Multipart uploads with resume, and adaptive Intelligent Ingestion on paid plans
- Storage
- Filestack storage, or your own Amazon S3, Google Cloud Storage or Azure container
- File size
- Limits depend on plan. See pricing
- Getting started
- Free plan with an API key. Compare plans
- Runs in
- The browser, and Node.js for server-side uploads
Upload a File in JavaScript in Three Steps
To upload a file in JavaScript with Filestack, install filestack-js, initialize the client with your API key, then open the picker or call client.upload(file). This js file upload takes three steps.
Install from npm, or load the same library with a script tag from the Filestack CDN.
One call creates the client with your API key. The picker handles selection, drag and drop, cloud sources and the upload itself.
client.upload()takes a File from any input and reports progress as it goes. The same multipart engine runs underneath.Every upload returns a handle, a CDN URL and the file's metadata.
$ npm install filestack-jsconst client = filestack.init('YOUR_API_KEY');
client.picker({
maxFiles: 5,
onUploadDone: (res) => console.log(res.filesUploaded),
}).open();
input.addEventListener('change', async () => {
const result = await client.upload(input.files[0], {
onProgress: (evt) => console.log(`${evt.totalPercent}%`),
});
console.log(result.handle, result.url);
});
"filename": "myfile.png",
"handle": "AFrHW1QRsWxmu5ZLU2qg",
"mimetype": "image/png",
"size": 1277297,
"source": "local_file_system",
"url": "https:/
"status": "Stored"
}
Capabilities of filestack-js: the JavaScript for upload, file validation, progress and resume, each turned on with one option. For large files on unstable networks, use chunked multipart uploads that resume.
Drag and drop file upload in JavaScript, plus paste from the clipboard.
dropPanemode turns any element into a drop target. For an example page, see JavaScript drag and drop file upload.JavaScript multiple file upload with one option.
maxFilessets the count, and File Picker 4.0 selects whole folders. To write it without a library, see upload multiple files in JavaScript.A JavaScript upload progress bar reads
totalPercentfrom each progress event, per file.acceptandmaxSizecheck files in the browser. Workflows add server-side checks after upload. To write the checks yourself, see file upload validation in JavaScript.Chunked file upload in JavaScript splits a large file into parts, retries failed parts and resumes after a dropped connection. Intelligent Ingestion adapts chunk size to the network on paid plans.
fromSourceslists the sources the picker shows, in the order you set.Users preview each image, then crop, rotate or circle-crop it before it uploads.
A small server endpoint signs a policy. Domain allow-lists limit uploads to your site, and virus detection runs on paid plans.
displayMode: 'dropPane',
container: '#drop-zone',
}).open();
minFiles: 1,
maxFiles: 20,
}).open();
client.picker({
onFileUploadProgress: (file, evt) => {
bar.value = evt.totalPercent;
},
}).open();
accept: ['image/*', '.pdf'],
maxSize: 25 * 1024 * 1024,
}).open();
intelligent: true,
retry: 5,
onProgress: (evt) => console.log(evt.totalPercent),
});
fromSources: ['local_file_system', 'googledrive',
'dropbox', 'webcam', 'url'],
}).open();
accept: 'image/*',
transformations: { crop: true, rotate: true, circle: true },
}).open();
const { policy, signature } = await res.json();
const client = filestack.init('YOUR_API_KEY', {
security: { policy, signature },
});
The Native Way to Upload a File With fetch and FormData
Native JavaScript uploads read the file from input.files[0], append it to FormData, and POST it with fetch. XMLHttpRequest adds upload progress through xhr.upload. For the form basics, see HTML file upload. For full code, see how to upload files using JavaScript and AJAX file upload.
-
Validate type and size
In the browser and again on the server. In filestack-js, set
acceptandmaxSize. -
Show progress
Read
xhr.uploadevents, oronProgressin filestack-js. -
Retry with resume
Upload large files in parts. filestack-js uses resumable multipart uploads by default.
-
Sign every request
Pass a policy your server signs to
securityin filestack-js.
const form = new FormData();
form.append('file', input.files[0]);
const response = await fetch('/upload', {
method: 'POST',
body: form,
});
const data = await response.json();
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
bar.value = (e.loaded / e.total) * 100;
}
});
xhr.open('POST', '/upload');
xhr.send(form);
Receive Uploads in Node.js, or Upload Straight to Storage
To integrate a file upload API with Node.js, let files go from the browser to Filestack storage or your own S3 bucket, and receive a signed webhook on your server. The native alternative is a Multer route.
Multer parses the multipart body and writes the file to disk. Storage, scanning and delivery are then yours to add.
Connect your bucket in the developer portal, then set
storeTo. Files land in your bucket, and Filestack still returns the handle and CDN URL.With Filestack, the file goes from the browser to Filestack storage or your S3 bucket. Your server receives a webhook signed with
FS-Signature, on paid plans.
import multer from 'multer';
const upload = multer({
dest: 'uploads/',
limits: { fileSize: 10 * 1024 * 1024 },
});
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ name: req.file.originalname, size: req.file.size });
});
app.listen(3000);
storeTo: { location: 's3', path: '/uploads/' },
}).open();
import express from 'express';
const app = express();
app.post('/filestack', express.raw({ type: '*/*' }), (req, res) => {
const signed = `${req.get('FS-Timestamp')}.${req.body}`;
const expected = crypto.createHmac('sha256', process.env.FS_WEBHOOK_SECRET)
.update(signed).digest('hex');
const given = Buffer.from(req.get('FS-Signature') || '');
if (given.length !== 64 || !crypto.timingSafeEqual(given, Buffer.from(expected))) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body);
console.log(event.action, event.text.url);
res.sendStatus(200);
});
Write It Yourself, Use an Open Source Library, or Use Filestack?
Building a JavaScript file uploader in-house means running endpoints, storage, resume, scanning and processing yourself. An open source library covers the interface, and a managed API like Filestack runs the rest.
| DIY fetch or XHR | Open source library (FilePond, Uppy, Dropzone) | Filestack | |
|---|---|---|---|
| UI | A file input you style | Prebuilt upload components | Prebuilt picker with drag and drop and paste |
| Backend | Your upload endpoint | Your upload endpoint, plus Uppy Companion for cloud imports | Hosted, plus a signing endpoint for secure uploads |
| Resumable uploads | Custom chunking code | Uppy with tus; chunked uploads in FilePond and Dropzone | Multipart with resume, and Intelligent Ingestion on paid plans |
| Cloud sources | Custom integrations | Uppy, through the Companion server you host | Google Drive, Dropbox, OneDrive, Box, URL, camera and more |
| Storage | Your server or bucket | Your server or bucket | Filestack storage, or your own S3, GCS or Azure |
| Virus scanning | Your own scanner | Your own scanner | Virus detection in Workflows, on paid plans |
| Image processing | Your own pipeline | Client-side editing plugins | URL transformations and Workflows |
| Cost | Your hosting and engineering time | Free library, plus your hosting | Free plan, then paid plans |
| Best for | Small internal tools | Teams with their own storage and ops | Teams that want upload, storage and processing handled |
DIY suits small internal tools, and an open source library suits teams that already run their own storage and operations.
Works With Your Framework
Official SDKs for React and Angular, and step-by-step guides for the rest.
After the Upload, Transform, Scan and Automate
Transform images and video on upload with URL tasks, and run scanning and OCR with Workflows, from the handle every upload returns.
Every upload returns a handle and a URL
- handle
- AFrHW1QRsWxmu5ZLU2qg
- url
- https://cdn.filestackcontent.com/AFrHW1QRsWxmu5ZLU2qg
Sample values from one upload.
-
URL transformations
Resize, crop and convert files by adding tasks to the CDN URL. Image transformations
https:// cdn.filestackcontent.com/ resize=width:400/ output=format:webp/ HANDLE -
Workflows on upload
Run virus scanning, OCR and tagging as files arrive, on paid plans. Workflows
-
Webhooks
Receive a signed event when an upload or workflow finishes, on paid plans. Webhooks
Ship JavaScript file upload today.
- Most teams ship their first upload in under a day
- Trusted by 100,000+ applications
- SOC 2 compliant
JavaScript File Upload FAQs
How do I upload a file using JavaScript?
Read the file from an input’s files list, append it to FormData, and POST it with fetch. With filestack-js, call client.upload(file) or open the picker, and the file goes straight to storage.
What is the difference between fetch and XMLHttpRequest for file uploads?
Both send multipart form data. XMLHttpRequest reports upload progress through xhr.upload progress events, while fetch has the simpler promise-based API. filestack-js reports progress through onProgress.
How do I show upload progress in JavaScript?
Listen for progress events on xhr.upload and divide loaded by total. In filestack-js, read evt.totalPercent in onProgress, or in onFileUploadProgress for the picker.
How do I upload large files in JavaScript?
Split the file into chunks and upload them with resume and retries. filestack-js does this with multipart uploads by default, and Intelligent Ingestion adapts chunk size to the network on paid plans.
What is the best JavaScript file upload library?
It depends on what you want to run. FilePond, Uppy and Dropzone are front-end libraries for teams with their own storage. filestack-js adds hosted upload, storage, cloud sources and processing in one package.
Do I need a server to upload files with JavaScript?
Filestack stores files straight from the browser, so storage needs no server of your own. Signed uploads use one small signing endpoint.
Is filestack-js free to use, and is there a free plan?
The library is open source, and Filestack has a free plan for getting started. Usage limits and paid features are on the pricing page.