This repo demonstrates how to load client-side (local) image files without requiring the user to manually encode their images to base-64 or to dangerously enable cross-site scripting (XSS) in their browsers.
You can compare the differences between my updated codes and the starter codes by checking this merge request.
Cross-site scripting (XSS) is dangerous because it allows unauthorized codes to access data from a different origin. All modern browsers follow the cross-origin resource sharing (CORS) policies given by the resource owners. Unfortunately, all local files are treated as from different origins due to security reasons. This protection mechanism hinders us from automatically loading anything from the users' local filesystems.
However, we can use FileReader
s to load local files. Note that this approach is fundamentally different from the XSS approach. The XSS approach treats the file to be loaded as a remote resource owned by the server side, and thus it has to follow the CORS policies. The FileReader
approach treats the file to be loaded as a local resource owned by the client (user) side, so the CORS mechanism is not involved at all.
HTML input
s have a type
attribute. One of the types is file
. An <input type="file">
element is rendered as a button. A pop-up window will appear for the user to select a file to be loaded once the button is clicked. A change
event will be triggered once the file finishes loading. Check my codes and the MDN documentation for more details.
Another way to load a file is to drag and drop one to the window. Check my codes and the MDN documentation for more details.