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

In browser JavaScript, convert an image URL to a named File by fetching it, checking response.ok, reading the response as a Blob, and passing that blob to the File constructor:

async function imageUrlToFile(url, filename) {
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error(`Image request failed: ${response.status}`);
  }

  const blob = await response.blob();

  return new File([blob], filename, {
    type: blob.type || "application/octet-stream",
    lastModified: Date.now()
  });
}

A Blob holds the downloaded bytes. A File is a blob with a filename and optional metadata, which makes it suitable for upload controls, FormData, and APIs that specifically require a file-like object.

What the conversion actually does

An image URL is only an address. It is not a local file and cannot be assigned directly to a file input. The browser must request the resource and expose its response body to JavaScript.

  1. Fetch the URL. fetch() returns a Response. It can resolve even when the server returns an HTTP error.
  2. Check the status. Test response.ok; it is true only for status codes from 200 through 299.
  3. Read the body. response.blob() creates a Blob containing the binary image data.
  4. Add file metadata. new File([blob], filename, options) gives those bytes a name, MIME type, and optional modification time.

The URL extension is not reliable evidence of the format. The server’s Content-Type, exposed through blob.type, is useful metadata, but applications handling untrusted uploads should validate the actual content as well.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty

A production-ready browser function

Basic conversion with a caller-supplied name

async function imageUrlToFile(url, filename, options = {}) {
  const {
    signal,
    maxBytes,
    allowedTypes
  } = options;

  const response = await fetch(url, { signal });

  if (!response.ok) {
    throw new Error(`Image request failed: HTTP ${response.status}`);
  }

  const blob = await response.blob();

  if (maxBytes !== undefined && blob.size > maxBytes) {
    throw new Error(`Image is ${blob.size} bytes; limit is ${maxBytes} bytes`);
  }

  const type = blob.type.toLowerCase();

  if (allowedTypes && !allowedTypes.includes(type)) {
    throw new Error(`Unsupported image type: ${type || "unknown"}`);
  }

  return new File([blob], filename, {
    type: type || "application/octet-stream",
    lastModified: Date.now()
  });
}

const file = await imageUrlToFile(
  "https://images.example.test/photo.webp",
  "profile-photo.webp",
  {
    maxBytes: 5 * 1024 * 1024,
    allowedTypes: ["image/jpeg", "image/png", "image/webp"]
  }
);

console.log(file.name, file.type, file.size);

filename is your decision. Choose an extension that matches the accepted format after checking the response metadata or validating the bytes. A URL may be extensionless, use a misleading extension, or contain an encoded path that is unsuitable as a filename.

Uploading the resulting File

const file = await imageUrlToFile(
  "https://images.example.test/photo.jpg",
  "avatar.jpg"
);

const form = new FormData();
form.append("avatar", file, file.name);

const uploadResponse = await fetch("/api/profile/avatar", {
  method: "POST",
  body: form
});

if (!uploadResponse.ok) {
  throw new Error(`Upload failed: HTTP ${uploadResponse.status}`);
}

Do not set the Content-Type header yourself when sending FormData. The browser adds the multipart boundary; replacing that header manually commonly produces an unreadable upload.

Cross-origin URLs and CORS

If the page and image are on different origins, the image server must allow your page’s origin with CORS. The browser applies CORS to a cross-origin fetch() by default. Without permission, JavaScript cannot read the response body, so it cannot create a usable blob or file.

Why mode: "no-cors" does not fix it

no-cors produces an opaque response. Its body and most headers are intentionally inaccessible to script, so response.blob() cannot provide the image bytes you need. It is not a client-side CORS bypass.

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

Options when the remote server allows no CORS

  • Ask the image host to return an Access-Control-Allow-Origin value that permits your application.
  • Fetch the image through a same-origin endpoint that you control.
  • Use a server-side proxy restricted to authorized URLs, with authentication, size limits, timeouts, and protections against server-side request forgery.

A proxy should not become an unrestricted “fetch any URL” service. Validate allowed hosts and schemes, limit redirects according to your policy, and reject unexpectedly large responses.

Blob, File, and object URLs: choose the right result

When a Blob is enough

Use the blob directly when a library accepts binary data and does not need a filename:

Rank #2
SANDISK 128GB Ultra Flair, USB-A Flash Drive, Up to 150MB/s Read Speeds
  • High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
  • Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
  • Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
  • Sleek, durable metal casing
  • Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]
const response = await fetch("https://images.example.test/photo.png");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
await imageProcessor(blob);

When you need a File

Use File when the receiving API expects name, type, and file semantics, such as a multipart upload or a component that normally receives a user-selected file. The bytes are the same; the additional metadata is what distinguishes the object.

When you only need a preview

An object URL previews a blob without converting it to a named file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const response = await fetch("https://images.example.test/photo.png");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
const previewUrl = URL.createObjectURL(blob);

const image = document.querySelector("#preview");
image.src = previewUrl;
image.addEventListener("load", () => {
  // Revoke it after the image and any later interaction no longer need it.
  URL.revokeObjectURL(previewUrl);
}, { once: true });

A blob: URL is temporary and local to the document. It is not a replacement for a File, and revoking it immediately can make a preview or later interaction unusable. Revoke URLs when the consumer is finished with them.

Cancellation, limits, and content validation

Cancel a slow request

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15_000);

try {
  const file = await imageUrlToFile(
    "https://images.example.test/large.jpg",
    "large.jpg",
    { signal: controller.signal }
  );
  console.log(file);
} catch (error) {
  if (error.name === "AbortError") {
    console.error("Image download was cancelled or timed out");
  } else {
    console.error(error);
  }
} finally {
  clearTimeout(timeoutId);
}

Cancellation stops waiting for the fetch; it does not make an unreliable origin reliable. Treat an abort separately from an HTTP error so the interface can offer “try again” rather than reporting a bad image.

Enforce a size limit

Check blob.size after reading the body, as in the production function. A Content-Length header can be absent or inaccurate, so it should not be your only safeguard. For stricter control, a server-side proxy can stream the response and stop once it exceeds a limit instead of buffering the entire file in browser memory.

Validate the actual image

blob.type is metadata supplied by the response and is not proof that the bytes are a valid JPEG, PNG, or WebP. For untrusted input, decode the image with an appropriate parser or image-processing service, enforce pixel and dimension limits, and reject files that do not meet your application’s policy. Do not trust the URL extension or a user-provided filename.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
2 Pack 64GB USB Flash Drive USB 2.0 Thumb Drives Jump Drive Fold Storage Memory Stick Swivel Design - Black
  • What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
  • Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
  • Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
  • Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
  • Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers

Browser versus server-side JavaScript

The recipe above targets browsers, where fetch, Blob, and File are standard web APIs. Server-side JavaScript runtimes differ in their versions and built-in implementations. Some provide web-compatible fetch, Blob, and File; others require a package or use a buffer-based upload API.

Keep the conversion boundary explicit: obtain a blob or byte buffer in the server runtime, then construct the runtime’s supported multipart/file object. Do not assume that browser globals, DOM APIs, or document exist on the server. If the same code must run in both environments, feature-detect the APIs or use an environment-specific adapter.

Common failures and fixes

“Fetch failed” or a CORS error

Cause: the remote origin refused your page or the network connection failed before an HTTP response was available.

Fix: inspect the browser console and Network panel, confirm the exact origin, configure CORS on the image host, or move the authorized fetch to your own server. no-cors will not expose the bytes.

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.

The function returns a File for a 404 page

Cause: code read the body without checking response.ok. A fetch promise can resolve for HTTP errors, and the body may be HTML rather than an image.

Fix: check response.ok before calling blob(), then validate the type and, when necessary, decode the bytes.

Rank #4
SIMMAX 32GB Memory Stick USB 2.0 Flash Drives Swivel Thumb Drive Pen Drive (32GB Purple)
  • GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
  • BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
  • EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
  • TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
  • WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.

The uploaded file has an empty or wrong type

Cause: the server omitted Content-Type, supplied a generic value, or your code replaced it.

Fix: inspect blob.type, apply only a trusted fallback, and validate the content before accepting it. The filename extension alone is not a reliable correction.

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

The preview disappears after a moment

Cause: its object URL was revoked before all consumers finished using it.

Fix: revoke the URL after the image has loaded and no later UI action needs it, or keep the URL until the component unmounts.

The browser runs out of memory

Cause: large responses, multiple retained blobs, or unreleased object URLs.

Fix: impose a size limit, process one image at a time where possible, release object URLs, and move large or untrusted downloads to a streaming server-side workflow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
IMEASON Swivel Design 16GB USB Flash Drive with Keychain, USB 2.0 Portable Thumb Drive Memory Stick, FAT32 Format Flashdrive for Data Storage, Photos, Music, Files (Black, 16 GB)
  • 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
  • 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
  • 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
  • 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
  • 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your real goal is a clean image of a web page rather than the original bytes at an image URL, ScreenshotNeo returns a screenshot through one request. Its API removes cookie and consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, and cache hits are not billed, with the result identified by response headers. It also provides an MCP server so Claude, Cursor, and other MCP clients can call take_screenshot, get_page_info, and capture_pdf.

See the parameter reference in the ScreenshotNeo documentation. A cURL request is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The same endpoint from Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

And from Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());

ScreenshotNeo includes full-page capture, element selection, device presets, custom CSS and JavaScript, waiting rules, request blocking, cookies and headers, PDF output, caching, signed links, asynchronous webhooks, bulk capture, and an OpenAPI specification. There are 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000, and every feature is available on every plan. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can I convert a data URL without making a network request?

Yes. Decode the data URL into bytes, create a Blob with its MIME type, and pass that blob to the File constructor. The fetch-based method is intended for HTTP(S) image URLs.

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 change the image format by changing the filename extension?

No. Renaming a File changes metadata only. Converting JPEG, PNG, WebP, or another format requires decoding and re-encoding the image with an image-processing API.

Does creating a File copy the image data?

The File is constructed from the blob’s file bits, so memory use still matters for large images. Release references and preview object URLs when they are no longer needed.

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.