October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Canvas API

How to Upload an html2canvas Image to a Database

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture the element with html2canvas(), export its canvas as a Blob with canvas.toBlob(), append that blob to FormData, and POST it to your own server. The server should validate the upload and then either store the image bytes in a binary-capable database column or put the file in object storage and save its key and metadata in the database. These are separate stages: html2canvas renders, the browser uploads, and your backend persists.

What happens between the page and the database

The browser should send an image file to an application endpoint, not connect directly to SQL with credentials embedded in client-side code. The endpoint authenticates the request, validates the file, and performs the persistence step. This keeps database credentials and storage decisions on the server.

  1. Capture: call html2canvas(element); it returns a Promise that resolves to a canvas.
  2. Encode: call canvas.toBlob() to produce binary image data.
  3. Upload: append the blob to FormData and send it with fetch().
  4. Validate and persist: the server checks the request and stores bytes or stores a file elsewhere with a database reference.

html2canvas is a browser-side renderer that reconstructs an image from DOM information and supported CSS. It is not a literal capture of the browser compositor, and some styling or content may differ from what the page visibly renders. See the html2canvas documentation for its rendering and compatibility limits.

Capture the element and upload it as a file

Install or otherwise load html2canvas in your application before running this function. Supply the actual element you want to capture and replace the example endpoint with your authenticated server route.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
async function captureAndUpload(element) {
  const canvas = await html2canvas(element, {
    // Works only when remote images grant cross-origin access.
    useCORS: true,
  });

  const blob = await new Promise((resolve, reject) => {
    canvas.toBlob((result) => {
      if (result) resolve(result);
      else reject(new Error('Canvas image could not be encoded'));
    }, 'image/png');
  });

  const formData = new FormData();
  formData.append('image', blob, 'capture.png');

  const response = await fetch('/api/images', {
    method: 'POST',
    body: formData,
    // Do not set Content-Type: the browser adds the multipart boundary.
  });

  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status}`);
  }
  return response.json();
}

For example, call captureAndUpload(document.querySelector('#receipt')) after confirming the element exists. The code assumes the endpoint accepts a multipart field named image, authenticates the user as appropriate, and returns JSON on success. Its route and response shape are application-specific; a server must also parse multipart form data.

Why the null check matters

toBlob() is asynchronous and its callback can receive null if the browser could not produce the image. The Promise wrapper turns that condition into a rejected operation instead of silently uploading an invalid value. The requested MIME type here is PNG. Browsers use PNG if the type is omitted or unsupported, but explicitly requesting the type makes the intended upload clearer. See MDN’s toBlob() reference.

Do not manually set the multipart content type

When a FormData body is passed to fetch(), the browser creates the multipart boundary and includes it in the request’s Content-Type. If you set Content-Type: multipart/form-data yourself, the required boundary may be missing and the server may not parse the fields. The MDN FormData guide describes using form data with Fetch.

Rank #2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
  • Easily store and access 5TB of content on the go with the Seagate portable drive, a USB external hard Drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Why use a Blob rather than a data URL?

canvas.toBlob() produces binary data that can be attached directly to FormData as a file-like field. By contrast, canvas.toDataURL() creates a base64-style data URL string. MDN recommends toBlob() for larger images because data URLs can have performance implications and can exceed URL length limits; the documentation does not define a universal size threshold. Use a data URL only if the receiving interface is explicitly designed for one. See MDN’s toDataURL() reference.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fix cross-origin images before exporting

A canvas that contains a cross-origin image without the necessary permission is not origin-clean. Browser security rules then prevent exporting its pixels; toBlob() can throw a SecurityError or fail to produce a blob. Setting useCORS: true asks html2canvas to load eligible resources with CORS, but it does not bypass the browser’s policy. The remote image host must send appropriate CORS permission. html2canvas documents the restriction and its proxy option at its documentation.

  • Inspect the browser console for CORS or canvas security errors.
  • Check the Network panel to see whether the image request succeeded and whether its response includes the required CORS headers.
  • If you control the image host, configure it to permit the origin that serves your application.
  • If you do not control the host, consider a carefully controlled server-side image proxy. Restrict destinations and validate requests; do not create an unrestricted proxy that can be abused to fetch internal or private network resources.

Even when export succeeds, unsupported CSS or rendering differences can make the result diverge from the visible page. If exact browser-pixel fidelity is essential, html2canvas’s DOM reconstruction may not meet that requirement.

Rank #3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
  • Easily store and access 1TB to content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop. Reformatting may be required for Mac
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Validate the file at the server boundary

Client-side checks are useful for feedback, but they are not security controls: a caller can bypass your page and send a crafted request directly. Apply upload controls on the server. The OWASP File Upload Cheat Sheet recommends controls such as these:

  • Allow only image formats the application actually needs.
  • Check the file’s content as well as its declared MIME type or filename; do not trust the request’s Content-Type header as proof of format.
  • Enforce a size limit appropriate to the application and reject oversized requests.
  • Require authorization and associate each upload with the correct user or record.
  • Generate the stored filename or object key on the server rather than trusting the client filename.
  • Store files outside the webroot or on a separate host where feasible, and serve them with the correct content type and access controls.

The client-side filename capture.png is only a multipart filename hint; it must not determine a trusted storage path. Validate and handle malformed, empty, or unexpectedly large uploads explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose how the server persists the image

“Upload to a database” can mean storing the image bytes in the database, or using the database to track an image held in file or object storage. Both are legitimate architectures; the appropriate choice depends on how your application uses and operates the files.

Rank #4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
  • Easily store and access 4TB of content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
Decision factor Database stores image bytes Object storage plus database reference
Transactional relationship Consider when the bytes need to participate directly in database transactions alongside related records. Consider when the database can store a key or reference separately from the object. Coordinating changes across storage systems requires application-level handling.
File size and volume Assess the effect of image bytes on database size and operations for your expected workload. Objects can hold file data and metadata; AWS describes this model in its S3 upload documentation.
Retrieval and serving Assess how the application reads and serves images from its database. Store the object key and related metadata in the database, then retrieve the object under the access controls your application needs.
Backup and restore Include image data in database backup and restore planning. Plan backups and recovery for the object store as well as the database reference.
Operations Keep image persistence within the database system, while accounting for its storage and maintenance needs. Operate a separate storage service and make sure object lifecycle, permissions, and database references stay consistent.

These are design questions, not evidence of a universal performance or cost winner. Database products differ in their binary column types and limits; use the type and parameterized APIs documented for the database you selected rather than treating a generic “BLOB” schema as portable.

Troubleshoot common failures

Symptom Likely cause What to check or change
html2canvas rejects or the element is missing The library is not loaded, the selector returned null, or capture ran before the relevant content was ready. Confirm the library import, check the element reference, and wait until the content to capture has been rendered.
Some images are missing A remote image failed to load, or its host did not permit CORS. Inspect console and network errors; enable useCORS only when the host permits it, or use a controlled proxy.
SecurityError on export The canvas is tainted by cross-origin content. Fix the resource’s CORS response or avoid including that resource. A client-side flag cannot override browser security.
toBlob() returns null The browser could not encode the canvas. Keep the null check and surface an actionable error; inspect browser console messages and the captured canvas.
Server reports malformed multipart data The request’s boundary may be absent because Content-Type was manually set. Remove the explicit header and let Fetch generate it for the FormData body.
Server returns 401 or 403 The request is unauthenticated or the user lacks permission for the target record. Send the application’s normal credentials or authorization token and enforce record-level authorization server-side.
Server rejects the file or request is too large The endpoint’s allowlist or size cap does not accept the upload. Check the actual encoded type and configured limit; reduce capture dimensions or choose an allowed format if suitable.
Image appears incorrect despite a successful upload html2canvas may not support a CSS feature or reproduce the browser’s exact rendering. Review the rendered canvas before uploading and consult html2canvas’s documented limitations.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

  • Canvas memory: a large capture occupies browser memory during rendering and encoding. Capture only the needed element and avoid unnecessarily large dimensions.
  • Encoding format: PNG is a lossless choice for many UI captures, but the supported output formats and quality behavior depend on the browser. Check the returned blob’s type and size rather than assuming encoding always succeeds.
  • Network and endpoint limits: uploads can fail because of connectivity, authentication expiry, request-size limits, or server errors. Show progress or retry controls where the application needs them; ensure retries do not create duplicate records unintentionally.
  • Persistence and serving: establish who can read each image, how long it is retained, and how it is removed when the associated record is deleted. Those policies belong to the application and storage design.

There is no universal file-size threshold or performance figure for this workflow. Measure capture and upload behavior with the actual element sizes, browsers, network conditions, and backend limits your application supports.

Or skip the browser setup

If your goal is a clean screenshot of a URL rather than a reconstruction of a particular DOM element, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns an image or PDF. For example, with cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
UnionSine 500GB Ultra Slim Portable External Hard Drive HDD-USB 3.0
  • [Upgraded Version] - This external hard drive features a mirrored logo stripe combined with a striped anti-slip design, and the rounded corners of the casing make it easier to grip. The stripes also have a heat dissipation function, ensuring stable and fast data transfer.
  • 【Ultra-thin and quiet】 - The motherboard adopts JMicron 578 noise-free solution, giving you a quiet working environment. Lightweight and portable size designed to fit in your pocket for easy portability.
  • 【Ultra-Fast Data Transfers】 - Pairing this external hard drive with JMicron 578 solution USB 3.0 and USB 2.0 interfaces enables blazing-fast data transfer. It boasts theoretical read speeds of up to 125MB/s and write speeds of up to 103MB/s.
  • 【Plug and Play】 - With no software to install, just plug it in and the drive is ready to use.The hard disk chip is wrapped with an aluminum anti-interference layer to increase heat dissipation and protect data.
  • 【What You Get】 - 1 x Portable Hard Drive, 1 x USB 3.0 Cable, 1 x User Manual, Gift-type shell packaging ,Three-year manufacturer's warranty and free technical support services.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options and authentication details. ScreenshotNeo removes cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server offers take_screenshot, get_page_info, and capture_pdf tools for AI agents. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Can html2canvas upload an image directly to SQL?

No. The browser sends the image to an application endpoint; server-side code validates it and performs database or object-storage persistence.

Does html2canvas capture exactly what the browser displays?

No. It reconstructs the image from DOM and supported CSS rather than taking a literal screenshot of the browser compositor.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I use a data URL instead of multipart upload?

Only if your receiving endpoint is explicitly designed to accept data URL strings; a Blob in FormData is the direct file-upload pattern.

Quick Recap

SaleBestseller No. 1
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.99
Bestseller No. 2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
Bestseller No. 3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.80
Bestseller No. 4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$151.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.