Home » Vulnerabilities Knowledge Base » Cross-Site Scripting (XSS) via File Upload
Cross-Site Scripting (XSS) via file upload occurs when a web application allows users to upload files and then serves those files back to users without validating or sanitizing their content or file type. If the uploaded file contains embedded JavaScript or executable code, and is later rendered in the browser, the attacker’s script can execute in the context of the user’s session.
If a user can upload .html, .svg, or .xml files and the server allows them to be accessed as-is, the attacker can inject JavaScript.
If the app stores and serves this file directly (e.g., via https://example.com/uploads/malicious.html), anyone visiting that link will execute the script.
Some attackers embed scripts into image file metadata (e.g., in SVG, PDF, or even malformed JPEGs), which are rendered by vulnerable image viewers or document readers in the browser.
Even if the file content is safe, malicious scripts can be injected through:
<script>alert(1)</script>.jpg)If these values are later rendered in HTML without proper escaping, they can also trigger XSS.
Session cookies or tokens can be stolen via malicious scripts.
Malicious scripts can rewrite DOM content, impersonate UI elements, or trick users.
XSS scripts can keylog input fields or exfiltrate CSRF tokens and personal data.
To prevent XSS via file upload, secure both the upload process and how files are stored/served.
Reject any file extensions or MIME types that browsers render as code:
Validate both file extension and MIME type using libraries like:
Prevent browsers from rendering files by setting headers.
This forces the browser to download the file instead of rendering it in-page.
Use image processing tools (like ExifTool or ImageMagick) to remove or sanitize metadata that might contain scripts.
Whether displaying filenames, captions, or custom fields — escape them properly using:
XSS via file upload is particularly dangerous because it looks like a harmless image or document, but silently compromises user sessions. Sanitize everything, validate every file, and serve user content in a sandbox.
Content Sniffing
Certain browsers, try to determine the content type and encoding of the response even when these properties are defined correctly...
Content Sniffing
Certain browsers, try to determine the content type and encoding of the response even when these properties are defined correctly...
Content Sniffing
Certain browsers, try to determine the content type and encoding of the response even when these properties are defined correctly...
Content Sniffing
Certain browsers, try to determine the content type and encoding of the response even when these properties are defined correctly...