Show a selected image’s filename literally beside its preview. Angle brackets and ampersands in that name should appear as characters on the page.
Read file.name from the selected File object, create a separate span for the label, and assign the name to that span’s textContent. Then append the span to the preview row. Do not interpolate the name into an HTML string and assign that string to innerHTML. The browser will parse HTML assigned to innerHTML; textContent inserts text instead.
Keep the label in its own element. Setting textContent replaces the element’s existing children, so assigning it to a row that already holds an image and a remove button will remove those children. Build the row once, and update only the label element when the selection changes.
Test the label renderer with synthetic filenames containing an ampersand and angle brackets. You can construct File objects for this test instead of depending on which characters your operating system allows in a real filename. Check that the characters appear literally and that the row still contains its preview and controls. The test does not need to decode an image: it exercises filename rendering only.
The filename label tells you nothing about whether the bytes decode as an image or pass an upload policy. Keep decoding, file limits and server validation as separate checks. Also avoid publishing real filenames in screenshots if those names contain private information.
References: https://developer.mozilla.org/en-US/docs/Web/API/File/name and https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent.
Top comments (0)