Contents
angular-file-upload-with-preview is a small Angular app from 2020 that shows a preview of an image, audio or video file as soon as you pick it. It runs on Angular 8.2 (@angular/core ~8.2.14 in package.json, CLI 8.3.21 according to the README) with TypeScript ~3.5.3, and it uses the ngx-dropzone package for the drop area. The repository is archived on GitHub, so it is read-only.
The name says file upload. The code previews files and never uploads them. The preview technique is short and still worth understanding, so I will start there.
Reading a file into a data URL
When a file is chosen, ngx-dropzone emits a change event and onSelect reads event.addedFiles. The preview comes from FileReader.readAsDataURL, wrapped in a promise (trimmed):
public async readFile(file: File): Promise<string | ArrayBuffer> {
return new Promise<string | ArrayBuffer>((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => resolve((e.target as FileReader).result);
reader.onerror = e => {
console.error(`FileReader failed on file ${file.name}.`);
return reject(null);
};
reader.readAsDataURL(file);
});
}The result is a data URL: the file's bytes, base64-encoded, in a string that starts with data: and the MIME type. The component keeps it in imageUrl, videoUrl or audioUrl, and the template binds it behind an *ngIf:
<img *ngIf="imageUrl" [src]="imageUrl" class="size">
<video *ngIf="videoUrl" class="size" autoplay controls>
<source [src]="videoUrl">
</video>The cost is that the browser must read the whole file and build the string before anything appears, and base64 is about a third larger than the file. That is fine for a photo and heavy for a video.
Telling the file types apart
The component never looks at the file's MIME type. It tests the file name against three regular expressions, in the order image, video, audio:
const regexImage = new RegExp('(.*?).(jpg|png|jpeg|svg|gif)$');
const regexVideo = new RegExp('(.*?).(mp4|3gp|ogg|wmv|flv|avi)$');
const regexAudio = new RegExp('(.*?).(mp3|oga|wav)$');Anything that matches none of them only logs "Invalid file type" to the console. Reading the patterns closely shows four problems:
- The dot before each group is not escaped, so it matches any character.
- There is no
iflag, soPHOTO.JPGis rejected. oggappears only in the video list and video is tested first, so an Ogg audio file is shown as video.wmv,flvandaviare listed as video, but matching an extension says nothing about whether the browser can play the file.
The audio branch and the sanitizer
Only the audio branch passes its data URL through DomSanitizer.bypassSecurityTrustResourceUrl. Angular sanitizes values bound to properties such as src, and that call tells it to trust a value as it is. No comment says why audio needs it and the other two do not. The audio <source> also hard-codes type="audio/mpeg", although the regex accepts oga and wav too.
What it does on upload
Nothing. HttpClientModule is imported in app.module.ts, and the component imports HttpClient, HttpRequest and other HTTP symbols, but no request is made anywhere in src/. The only trace of upload is a comment repeated three times, "Put this string in a request body to upload it to an API." The allFiles array that feeds the preview list is never filled, so that list, which would print file.type, never renders. The drop label says "Please drop image or video!", though audio is supported.
What I would change today
Everything here is visible in the current code.
- Use an object URL.
URL.createObjectURL(file)points at the file without reading it into a string, which matters most for video, andURL.revokeObjectURLinonRemovedfrees it. ThereadFilepromise would go away. - Use
file.type. Something likefile.type.startsWith('image/')is the browser's own answer. The template already refers tofile.type. - Read one file.
onSelectloops overaddedFiles, callsonRemoved()on every pass and pushes the whole list each time. It only behaves because the dropzone has[multiple]="false". Readingevent.addedFiles[0]once is simpler. - Handle failure. The three
readFile(...).then(...)calls have no.catch, and a bad file type shows nothing to the user. - Upload the file itself. Send the
Filein aFormDatathroughHttpClient, not the base64 string the comments suggest. - Tidy up. Remove the unused imports, the
anyfields and the commented-out S3 URLs. The CLI-generated spec still expects a title and text the component no longer has.
As a demo of the preview idea, it is enough to learn from. As the base of a real upload form, I would keep the dropzone and replace the reading and the type check first.
Found this useful? Share it with your team.