Client‑Side Image Compression and Upload Using HTML5 FileReader and Canvas
This article explains how to implement client‑side image compression in mobile browsers by converting selected files to DataURL, resizing them with a Canvas element, adjusting compression rates based on file size, and finally uploading the compressed Blob to a server via AJAX.
In many web applications users need to upload high‑resolution photos, but server limits (e.g., 2 MB) require client‑side size reduction. The solution leverages HTML5 APIs: the FileReader reads the selected file, converts it to a DataURL, and then a canvas element resizes and recompresses the image.
The workflow is:
Listen for the change event on an input[type="file"] element.
If FileReader is unavailable, upload the original file directly.
Otherwise, read the file as a DataURL, create an Image object, and draw it onto a canvas sized to the desired width/height (default 800 × 600).
Adjust the canvas dimensions proportionally when the original image exceeds the maximum size.
Determine a compression rate based on the original file size (e.g., 0.6 for < 2 MB, 0.4 for 2‑4 MB, 0.3 for 4‑8 MB, 0.2 for > 8 MB).
Export the canvas to a JPEG DataURL using canvas.toDataURL('image/jpeg', rate) , convert that DataURL back to a Blob , and invoke the upload routine.
Utility functions included:
function readBlobAsDataURL(blob, callback) { ... } function dataURLtoBlob(dataurl) { ... } function readBase64AsBlob(option) { ... } function compressUploadImageAsClient(option) { ... }The postFileToServer function builds a FormData object, appends the compressed file, and sends it via XMLHttpRequest with appropriate success, error, and abort callbacks.
Overall, this approach minimizes network transfer, ensures the uploaded image retains sufficient quality for document verification, and provides a responsive user experience on mobile browsers.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.