angular-material-datatransfer-lib v4.0.3
angular-material-datatransfer-lib
Demo: https://niklr.github.io/angular-material-datatransfer/
angular-material-datatransfer-lib is a library combining the upload and download of multiple simultaneous files in a unified user interface.
The library is explicitly designed for modern browsers supporting advanced HTML5 File API features.
The unified user interface is built on top of Google's Material Design implemented by Angular Material using Angular. Material Design by Google's definition is a visual language that synthesizes the classic principles of good design with the innovation and possibility of technology and science.
For multiple simultaneous uploads the open-source library called Resumable.js is used. Resumable.js introduces fault-tolerance into the upload of large files through HTTP. This is done by splitting each file into small chunks. Then, whenever the upload of a chunk fails, uploading is retried until the procedure completes. This allows uploads to automatically resume uploading after a network connection is lost either locally or to the server. Additionally, it allows for users to pause, resume and even recover uploads without losing state because only the currently uploading chunks will be aborted, not the entire upload.
For multiple simultaneous downloads the open-source library called FileSaver.js is used.
FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.
Table of Content:
Basic setup
A sample implementation can be found here. It was created with ng new example1 of Angular CLI.
In order to add this library to your project, follow the steps below:
- npm install angular-material-datatransfer-lib --save
- Add the dependencies listed in
peerDependencies(node_modules/angular-material-datatransfer-lib/package.json) to thedependenciesin your package.json - npm install
- Extend your
angular.jsonby appending the following lines after the global styles build entry.
"styles": [
...
],
"stylePreprocessorOptions": {
"includePaths": [
"node_modules"
]
},
"scripts": [
...
]- Add
angular-material.scssto yoursrcfolder (if it does not exist already). - Add a folder called
stylein thesrcfolder with the following files
- Append the following lines in
src/styles.scss
@import 'angular-material.scss';
@import 'style/app.scss';- Include Material Icons in the header of
index.html
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">- Extend
app.module.tsby importingAngularMaterialDatatransferModuleandAngularMaterialDatatransferComponent
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularMaterialDatatransferModule, AngularMaterialDatatransferComponent } from 'angular-material-datatransfer-lib';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
AngularMaterialDatatransferModule
],
providers: [AngularMaterialDatatransferComponent],
bootstrap: [AppComponent]
})
export class AppModule { }- Add the library to one of your components e.g.
app.component.html
<angular-material-datatransfer-lib>Loading...</angular-material-datatransfer-lib>- Initialize the library
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { AngularMaterialDatatransferComponent } from 'angular-material-datatransfer-lib';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
@ViewChild(AngularMaterialDatatransferComponent, {static: false}) amdComponent: AngularMaterialDatatransferComponent;
constructor() {
}
ngAfterViewInit(): void {
setTimeout(() => {
const config = {
core: {
showUploadDropzone: true,
paginationRppOptions: [5, 10, 25],
preprocessHashEnabled: true,
preprocessHashChecked: false
},
resumablejs: {
simultaneousUploads: 2,
preprocess: function (chunk) {
// do something with the chunk
chunk.preprocessFinished();
}
}
};
this.amdComponent.create(config);
}, 10);
}
}Handling download
The download of a file can be triggered by invoking the download function with the following arguments:
filenameThe name of the file to be downloaded.urlThe URL of the file to be downloaded.sizeThe size in bytes of the file to be downloaded.
this.amdComponent.download(filename, url, size);Events
After initialization, it is possible to listen to events initiated by angular-material-datatransfer:
document.addEventListener('github:niklr/angular-material-datatransfer.upload-completed', function (e) { ... });github:niklr/angular-material-datatransfer.upload-completedIndicates that the overall upload has been completed.github:niklr/angular-material-datatransfer.download-completedIndicates that the overall download has been completed.github:niklr/angular-material-datatransfer.item-addedIndicates that an item has been added. It will be passed a IDatatransferItem as detail payload.github:niklr/angular-material-datatransfer.item-removedIndicates that an item has been removed. It will be passed a IDatatransferItem as detail payload.github:niklr/angular-material-datatransfer.item-completedIndicates that an item has been completed.github:niklr/angular-material-datatransfer.items-clearedIndicates that all items have been cleared.
Configuration
In order to initialize and configure angular-material-datatransfer, a custom event called github:niklr/angular-material-datatransfer.create can be dispatched on the document object. The configuration differentiates between core and resumablejs. Both are described below.
var config = {
production: boolean // corresponds to the environment variable (Default: true)
core: {
...
},
resumablejs: {
...
}
};
var event = new CustomEvent('github:niklr/angular-material-datatransfer.create', { 'detail': config });
document.dispatchEvent(event);Core configuration
showUploadDropzoneIndicates if the built-in dropzone element enabling the user to drop folders/files to be uploaded should be shown. (Default:'true')uploadBrowseElementIdThe identifier of the element enabling the user to add files to be uploaded. (Default:undefined)uploadDropElementIdThe identifier of the element enabling the user to drop folders/files to be uploaded. (Default:undefined)paginationRppOptionsThe pagination options containing the numbers defining how many results should be shown per page. (Default:[5, 10, 25])simultaneousDownloadsNumber of simultaneous downloads. (Default:2)downloadMethodHTTP method to use when downloading from the server (GET,POST,PUT,PATCH). (Default:GET)downloadHeadersExtra headers to include in the multipart POST with data. This can be anobjector afunctionthat allows you to construct and return a value, based on suppliedfile(Default:{})downloadWithCredentialsStandard CORS requests used for downloading do not send or set any cookies by default. In order to include cookies as part of the request, you need to set the property to true. (Default:false)downloadXhrTimeoutThe timeout in milliseconds for each download request (Default:0)preprocessHashEnabledIndicates if the built-in preprocess hash module should be enabled. (Default:'false')preprocessHashCheckedIndicates if the checkbox for the built-in preprocess hash module should be checked. (Default:'true')preprocessHashTargetThe target URL for the GET request to the server for each file to see if it already exists based on the in-browser calculated hash. This can be astringor afunctionthat allows you you to construct and return a value, based on suppliedparams. (Default:https://httpbin.org)preprocessHashMethodHTTP method to use when sending file preprocess hash requests. (Default:'GET')preprocessHashParameterNameThe name of the preprocess hash request parameter for the hash. (Default:'hash')preprocessHashFileNameParameterNameThe name of the preprocess hash request parameter for the file name. (Default:'filename')preprocessHashFunctionNameThe name of the hash function to be used in the built-in preprocess hash module. (sha1,md5) (Default:'sha1')preprocessHashEncodingNameThe name of the encoding scheme to be used in the built-in preprocess hash module. (latin1,hex,base64,utf8) (Default:'hex')preprocessHashInputEncodingNameThe name of the input encoding scheme to be used in the built-in preprocess hash module. (latin1,hex,base64,utf8) (Default:'latin1')preprocessHashTooltipContentThe text to explain the preprocess option in a tooltip. (Default:'The preprocess option checks if the file is already on the system before uploading.')parseMessageCallbackA function which displays the status message of an uploaded item. (Default: displays the raw result of an uploaded item as returned by the API endpoint)
Resumablejs configuration
targetThe target URL for the multipart POST request. This can be astringor afunctionthat allows you you to construct and return a value, based on suppliedparams. (Default:https://httpbin.org)testTargetThe target URL for the GET request to the server for each chunk to see if it already exists. This can be astringor afunctionthat allows you you to construct and return a value, based on suppliedparams. (Default:null)chunkSizeThe size in bytes of each uploaded chunk of data. The last uploaded chunk will be at least this size and up to two the size, see Issue #51 for details and reasons. (Default:1*1024*1024)forceChunkSizeForce all chunks to be less or equal than chunkSize. Otherwise, the last chunk will be greater than or equal tochunkSize. (Default:false)simultaneousUploadsNumber of simultaneous uploads (Default:3)fileParameterNameThe name of the multipart request parameter to use for the file chunk (Default:file)chunkNumberParameterNameThe name of the chunk index (base-1) in the current upload POST parameter to use for the file chunk (Default:resumableChunkNumber)totalChunksParameterNameThe name of the total number of chunks POST parameter to use for the file chunk (Default:resumableTotalChunks)chunkSizeParameterNameThe name of the general chunk size POST parameter to use for the file chunk (Default:resumableChunkSize)totalSizeParameterNameThe name of the total file size number POST parameter to use for the file chunk (Default:resumableTotalSize)identifierParameterNameThe name of the unique identifier POST parameter to use for the file chunk (Default:resumableIdentifier)fileNameParameterNameThe name of the original file name POST parameter to use for the file chunk (Default:resumableFilename)relativePathParameterNameThe name of the file's relative path POST parameter to use for the file chunk (Default:resumableRelativePath)currentChunkSizeParameterNameThe name of the current chunk size POST parameter to use for the file chunk (Default:resumableCurrentChunkSize)typeParameterNameThe name of the file type POST parameter to use for the file chunk (Default:resumableType)queryExtra parameters to include in the multipart request with data. This can be an object or a function. If a function, it will be passed a ResumableFile and a ResumableChunk object (Default:{})testMethodMethod for chunk test request. (Default:'GET')uploadMethodHTTP method to use when sending chunks to the server (POST,PUT,PATCH) (Default:POST)parameterNamespaceExtra prefix added before the name of each parameter included in the multipart POST or in the test GET. (Default:'')headersExtra headers to include in the multipart POST with data. This can be anobjector afunctionthat allows you to construct and return a value, based on suppliedfile(Default:{})methodMethod to use when sending chunks to the server (multipartoroctet) (Default:multipart)prioritizeFirstAndLastChunkPrioritize first and last chunks of all files. This can be handy if you can determine if a file is valid for your service from only the first or last chunk. For example, photo or video meta data is usually located in the first part of a file, making it easy to test support from only the first chunk. (Default:false)testChunksMake a GET request to the server for each chunks to see if it already exists. If implemented on the server-side, this will allow for upload resumes even after a browser crash or even a computer restart. (Default:true)preprocessOptional function to process each chunk before testing & sending. Function is passed the chunk as parameter, and should call thepreprocessFinishedmethod on the chunk when finished. (Default:null)generateUniqueIdentifier(file, event)Override the function that generates unique identifiers for each file. May return Promise-like object withthen()method for asynchronous id generation. Parameters are the ESFileobject and the event that led to adding the file. (Default:null)maxFilesIndicates how many files can be uploaded in a single session. Valid values are any positive integer andundefinedfor no limit. (Default:undefined)maxFilesErrorCallback(files, errorCount)A function which displays the please upload n file(s) at a time message. (Default: displays an alert box with the message Please n one file(s) at a time.)minFileSizeThe minimum allowed file size. (Default:undefined)minFileSizeErrorCallback(file, errorCount)A function which displays an error a selected file is smaller than allowed. (Default: displays an alert for every bad file.)maxFileSizeThe maximum allowed file size. (Default:undefined)maxFileSizeErrorCallback(file, errorCount)A function which displays an error a selected file is larger than allowed. (Default: displays an alert for every bad file.)fileTypeThe file types allowed to upload. An empty array allow any file type. (Default:[])fileTypeErrorCallback(file, errorCount)A function which displays an error a selected file has type not allowed. (Default: displays an alert for every bad file.)maxChunkRetriesThe maximum number of retries for a chunk before the upload is failed. Valid values are any positive integer andundefinedfor no limit. (Default:undefined)chunkRetryIntervalThe number of milliseconds to wait before retrying a chunk on a non-permanent error. Valid values are any positive integer andundefinedfor immediate retry. (Default:undefined)withCredentialsStandard CORS requests do not send or set any cookies by default. In order to include cookies as part of the request, you need to set thewithCredentialsproperty to true. (Default:false)xhrTimeoutThe timeout in milliseconds for each request (Default:0)
Server-side setup
Most of the magic happens in the user's browser, but files still need to be reassembled from chunks on the server side. This should be a fairly simple task, which and can be achieved using any web framework or language that is capable of handling file uploads.
To handle the state of upload chunks, a number of extra parameters are sent along with all requests:
resumableChunkNumber: The index of the chunk in the current upload. First chunk is1(no base-0 counting here).resumableTotalChunks: The total number of chunks.resumableChunkSize: The general chunk size. Using this value andresumableTotalSizeyou can calculate the total number of chunks.resumableCurrentChunkSize: The current chunk size. Please note that this value might be lower or higher thanresumableChunkSizefor the last chunk of a file.resumableTotalSize: The total file size.resumableIdentifier: A unique identifier for the file contained in the request.resumableFilename: The original file name (since a bug in Firefox results in the file name not being transmitted in chunk multipart posts).resumableRelativePath: The file's relative path when selecting a directory (defaults to file name in all browsers except Chrome).
You should allow for the same chunk to be uploaded more than once; this isn't standard behaviour, but on an unstable network environment it could happen.
For every request, you can confirm reception in HTTP status codes (can be change through the permanentErrors option):
200: The chunk was accepted and correct. No need to re-upload.400,404,405,415,501: The file for which the chunk was uploaded is not supported, cancel the entire upload.- Anything else: Something went wrong, but try reuploading the file.