Why do browsers hide the full local file path (C:\fakepath) on <input type="file">? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

Why do browsers hide the full local file path (C:\fakepath) on <input type="file">?

message-square
0

Browsers hide the full local file path on <input type="file">—commonly replacing it with C:\fakepath\<filename> when reading input.value—as a security and privacy defense against leaking local filesystem structure, usernames, and directory paths to untrusted web pages, while also keeping legacy compatibility with scripts that expect a fake path prefix rather than an empty string or raw local path. Instead of parsing input.value for a path, modern web code reads selected files through input.files (FileList / File objects containing .name, .size, .type, and .lastModified) and uploads them via FormData or reads contents with File.text() / File.arrayBuffer() / FileReader.


1. Security Rationale and Safely Reading Selected Files via input.files

Exposing full local paths like C:\Users\Tariq\Documents\tax-2026.pdf or /home/tariq/projects/secrets/key.pem reveals OS conventions, account usernames, and folder hierarchies that attackers can combine with social engineering or other vulnerabilities. Always validate the input element and read input.files (FileList) rather than relying on input.value:

// Safely inspect selected File entries from an <input type="file"> element
function inspectSelectedFiles(fileInput) {
  if (!(fileInput instanceof HTMLInputElement) || fileInput.type !== "file") {
    throw new TypeError("Expected fileInput to be an <input type=\"file\"> element.");
  }

  try {
    const fileList = fileInput.files;
    if (!fileList || fileList.length === 0) {
      return new Map();
    }

    const metadataByName = new Map();
    for (let i = 0; i < fileList.length; i += 1) {
      const file = fileList[i];
      if (!(file instanceof File)) {
        continue;
      }

      metadataByName.set(i, {
        name: file.name,
        size: file.size,
        mimeType: file.type || "application/octet-stream",
        lastModified: file.lastModified
      });
    }

    return metadataByName;
  } catch (error) {
    throw new Error(`Failed reading selected files: ${error.message}`);
  }
}

// Example usage:
// try {
//   const inputEl = document.querySelector('input[type="file"]');
//   const filesMap = inspectSelectedFiles(inputEl);
//   console.log("Selected files:", filesMap);
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Never parse C:\fakepath\ to recover the real directory: The real path is intentionally withheld by the browser and cannot be reconstructed from input.value.
  • Use file.name (sanitized on the server) for display or filename checks: file.name gives the base filename without local directory structure.

2. Building a FormData Upload Payload Without Relying on Local Paths

When uploading files to an API or backend endpoint (fetch / $.ajax / XMLHttpRequest), append File / Blob instances directly to a FormData payload—do not attempt to pass local filesystem paths to the server: // Build a validated FormData payload from a file input’s FileList function createUploadFormData(fileInput, { fieldName = “files”, maxBytesPerFile = 10 * 1024 * 1024 } = {}) { if (!(fileInput instanceof HTMLInputElement) \vert{}\vert{} fileInput.type !== “file”) { throw new TypeError(“Expected fileInput to be an <input type="file"> element.”); } if (typeof fieldName !== “string” \vert{}\vert{} fieldName.trim().length === 0) { throw new TypeError(“Expected fieldName to be a non-empty string.”); } if (typeof maxBytesPerFile !== “number” \vert{}\vert{} !Number.isFinite(maxBytesPerFile) \vert{}\vert{} maxBytesPerFile <= 0) { throw new RangeError(“Expected maxBytesPerFile to be a positive finite number.”); } try { const formData = new FormData(); const files = fileInput.files; if (!files \vert{}\vert{} files.length === 0) { throw new Error(“No file selected in file input.”); } for (let i = 0; i < files.length; i += 1) { const item = files[i]; if (!(item instanceof File)) { continue; } if (item.size > maxBytesPerFile) { throw new RangeError(File "${item.name}" (${item.size} bytes) exceeds limit of${maxBytesPerFile} bytes.); }

      formData.append(fieldName.trim(), item, item.name);
    }

    return formData;
  } catch (error) {
    throw new Error(`Failed constructing upload FormData: ${error.message}`); } }  // Example usage: // try { //   const picker = document.querySelector("#avatar-upload"); //   const payload = createUploadFormData(picker, { fieldName: "avatar", maxBytesPerFile: 5 * 1024 * 1024 }); //   // fetch("/api/upload", { method: "POST", body: payload }); // } catch (error) { //   console.error(`${error.name}: ${error.message}`); // }  - **Let the browser set the `multipart/form-data` boundary automatically with `FormData`:** Do not manually override `Content-Type` when sending `FormData` in `fetch` or `$.ajax`.
  • Validate file size and MIME/extension rules on both client and server: Client checks improve UX, while server checks enforce security.

3. Why C:\fakepath\ Exists and Common File-Input Gotchas

Understanding how browsers standardize C:\fakepath\ helps prevent surprises in legacy and modern web apps:

  • Historical compatibility with path-parsing scripts: Older web forms sometimes split input.value on \ or /; prefixing C:\fakepath\ satisfied legacy path-splitting assumptions without leaking real folders.
  • You cannot pre-populate <input type="file"> with an arbitrary local path or file: For security, scripts cannot set input.value = "C:\\secret.txt" (only "" to clear the selection).
  • Resetting a file input (input.value = "") clears input.files: Always clear via input.value = "" when resetting a form or allowing re-selection of the same file.