UNPKG

9.38 kBMarkdownView Raw
1# ngx-uploader
2
3Angular 2+ File Uploader
4
5http://ngx-uploader.com
6
7#### <a name="question"></a> Got a Question or Problem?
8
9Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on [Stack Overflow](https://stackoverflow.com) where the questions should be tagged with tag `ngx-uploader`.
10
11To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.
12
13## Installation
14
151. Add `ngx-uploader` module as dependency to your project.
16
17```console
18npm install ngx-uploader --save
19```
20
212. Include `NgxUploaderModule` into your main AppModule or in module where you will use it.
22
23```ts
24// app.module.ts
25import { NgModule } from '@angular/core';
26import { BrowserModule } from '@angular/platform-browser';
27import { NgxUploaderModule } from 'ngx-uploader';
28
29@NgModule({
30 imports: [BrowserModule, NgxUploaderModule],
31 declarations: [AppComponent]
32})
33export class AppModule {}
34```
35
36**or** include `NgxUploaderModule` into your SharedModule. This could be usefull if your project has nested Modules.
37
38```ts
39// shared.module.ts
40import { NgModule } from '@angular/core';
41import { CommonModule } from '@angular/common';
42import { NgxUploaderModule } from 'ngx-uploader';
43...
44
45@NgModule({
46 imports: [
47 CommonModule,
48 NgxUploaderModule,
49 ...
50 ],
51 exports: [
52 CommonModule,
53 NgxUploaderModule,
54 ...
55 ],
56 ...
57})
58export class SharedModule {
59}
60```
61
62```ts
63// app.module.ts
64import { NgModule } from '@angular/core';
65import { BrowserModule } from '@angular/platform-browser';
66import { SharedModule } from './shared.module';
67
68@NgModule({
69 imports: [BrowserModule, SharedModule],
70 declarations: [AppComponent]
71})
72export class AppModule {}
73```
74
75## Data Structures of Events and Uploaded Files
76
77```ts
78export interface UploaderOptions {
79 concurrency: number; // number of files uploaded at the same time
80 allowedContentTypes?: string[]; // content types allowed (default *)
81 maxUploads?: number; // max number of files the user can upload
82 maxFileSize?: number; // max size of the file in bytes the user can upload
83}
84
85export interface UploadProgress {
86 status: UploadStatus; // current status of upload for specific file (Queue | Uploading | Done | Canceled)
87 data?: {
88 percentage: number; // percentage of upload already completed
89 speed: number; // current upload speed per second in bytes
90 speedHuman: string; // current upload speed per second in human readable form,
91 eta: number; // estimated time remaining in seconds
92 etaHuman: string; // estimated time remaining in human readable format
93 };
94}
95
96export interface UploadFile {
97 id: string; // unique id of uploaded file instance
98 fileIndex: number; // fileIndex in internal ngx-uploader array of files
99 lastModifiedDate: Date; // last modify date of the file (Date object)
100 name: string; // original name of the file
101 size: number; // size of the file in bytes
102 type: string; // mime type of the file
103 form: FormData; // FormData object (you can append extra data per file, to this object)
104 progress: UploadProgress;
105 response?: any; // response when upload is done (parsed JSON or string)
106 responseStatus?: number; // response status code when upload is done
107 responseHeaders?: { [key: string]: string }; // response headers when upload is done
108}
109
110// output events emitted by ngx-uploader
111export interface UploadOutput {
112 type:
113 | 'addedToQueue'
114 | 'allAddedToQueue'
115 | 'uploading'
116 | 'done'
117 | 'removed'
118 | 'start'
119 | 'cancelled'
120 | 'dragOver'
121 | 'dragOut'
122 | 'drop';
123 file?: UploadFile;
124 nativeFile?: File; // native javascript File object, can be used to process uploaded files in other libraries
125}
126
127// input events that user can emit to ngx-uploader
128export interface UploadInput {
129 type: 'uploadAll' | 'uploadFile' | 'cancel' | 'cancelAll' | 'remove' | 'removeAll';
130 url?: string; // URL to upload file to
131 method?: string; // method (POST | PUT)
132 id?: string; // unique id of uploaded file
133 fieldName?: string; // field name (default 'file')
134 fileIndex?: number; // fileIndex in internal ngx-uploader array of files
135 file?: UploadFile; // uploading file
136 data?: { [key: string]: string | Blob }; // custom data sent with the file
137 headers?: { [key: string]: string }; // custom headers
138 includeWebKitFormBoundary?: boolean; // If false, only the file is send trough xhr.send (WebKitFormBoundary is omit)
139 concurrency?: number; // concurrency of how many files can be uploaded in parallel (default is 0 which means unlimited)
140 withCredentials?: boolean; // apply withCredentials option
141}
142```
143
144## Upload Restrictions
145
146With version 4.2.1 we've introduced restrictions for Content-Types.
147To not break the behaviour of previous releases, there are no restrictions by default at all.
148
149Look at [app-home.component.ts](https://github.com/bleenco/ngx-uploader/blob/master/src/components/app-home/app-home.component.ts) for an example of Content-Type restriction.
150
151If you want to toast a message for the rejected file, add this to your onUploadOutput method.
152
153```ts
154onUploadOutput(output: UploadOutput): void {
155....
156} else if (output.type === 'rejected' && typeof output.file !== 'undefined') {
157 // console.log(output.file.name + ' rejected');
158}
159...
160```
161
162## Token Authorization
163
164If you have to upload files with Token Authorization, you can set the header in startUpload as follows.
165
166```ts
167startUpload(): void {
168 let token = this.myToken; // <---- get token
169 const event: UploadInput = {
170 type: 'uploadAll',
171 url: 'http://ngx-uploader.com/upload',
172 method: 'POST',
173 headers: { 'Authorization': 'JWT ' + token }, // <---- set headers
174 data: { foo: 'bar' },
175 includeWebKitFormBoundary: true // <---- set WebKitFormBoundary
176 };
177
178 this.uploadInput.emit(event);
179}
180```
181
182## Example
183
184**You can always run working example by cloning this repository, building project with `yarn build:prod` and running server with `node ./dist-app/api/index.js`.**
185
186### Component Code
187
188```ts
189import { Component, EventEmitter } from '@angular/core';
190import { UploadOutput, UploadInput, UploadFile, humanizeBytes, UploaderOptions } from 'ngx-uploader';
191
192@Component({
193 selector: 'app-home',
194 templateUrl: 'app-home.component.html'
195})
196export class AppHomeComponent {
197 options: UploaderOptions;
198 formData: FormData;
199 files: UploadFile[];
200 uploadInput: EventEmitter<UploadInput>;
201 humanizeBytes: Function;
202 dragOver: boolean;
203
204 constructor() {
205 this.options = { concurrency: 1, maxUploads: 3, maxFileSize: 1000000 };
206 this.files = []; // local uploading files array
207 this.uploadInput = new EventEmitter<UploadInput>(); // input events, we use this to emit data to ngx-uploader
208 this.humanizeBytes = humanizeBytes;
209 }
210
211 onUploadOutput(output: UploadOutput): void {
212 switch (output.type) {
213 case 'allAddedToQueue':
214 // uncomment this if you want to auto upload files when added
215 // const event: UploadInput = {
216 // type: 'uploadAll',
217 // url: '/upload',
218 // method: 'POST',
219 // data: { foo: 'bar' }
220 // };
221 // this.uploadInput.emit(event);
222 break;
223 case 'addedToQueue':
224 if (typeof output.file !== 'undefined') {
225 this.files.push(output.file);
226 }
227 break;
228 case 'uploading':
229 if (typeof output.file !== 'undefined') {
230 // update current data in files array for uploading file
231 const index = this.files.findIndex(file => typeof output.file !== 'undefined' && file.id === output.file.id);
232 this.files[index] = output.file;
233 }
234 break;
235 case 'removed':
236 // remove file from array when removed
237 this.files = this.files.filter((file: UploadFile) => file !== output.file);
238 break;
239 case 'dragOver':
240 this.dragOver = true;
241 break;
242 case 'dragOut':
243 case 'drop':
244 this.dragOver = false;
245 break;
246 case 'done':
247 // The file is downloaded
248 break;
249 }
250 }
251
252 startUpload(): void {
253 const event: UploadInput = {
254 type: 'uploadAll',
255 url: 'http://ngx-uploader.com/upload',
256 method: 'POST',
257 data: { foo: 'bar' }
258 };
259
260 this.uploadInput.emit(event);
261 }
262
263 cancelUpload(id: string): void {
264 this.uploadInput.emit({ type: 'cancel', id: id });
265 }
266
267 removeFile(id: string): void {
268 this.uploadInput.emit({ type: 'remove', id: id });
269 }
270
271 removeAllFiles(): void {
272 this.uploadInput.emit({ type: 'removeAll' });
273 }
274}
275```
276
277### Template Code
278
279For whole template code please check [here](https://github.com/bleenco/ngx-uploader/blob/master/src/components/app-home/app-home.component.html).
280
281```html
282<div
283 class="drop-container"
284 ngFileDrop
285 [options]="options"
286 (uploadOutput)="onUploadOutput($event)"
287 [uploadInput]="uploadInput"
288 [ngClass]="{ 'is-drop-over': dragOver }"
289>
290 <h1>Drag &amp; Drop</h1>
291</div>
292
293<label class="upload-button">
294 <input
295 type="file"
296 ngFileSelect
297 [options]="options"
298 (uploadOutput)="onUploadOutput($event)"
299 [uploadInput]="uploadInput"
300 multiple
301 />
302 or choose file(s)
303</label>
304
305<button type="button" class="start-upload-btn" (click)="startUpload()">
306 Start Upload
307</button>
308```
309
310### LICENCE
311
312MIT