we are trying to set a limit on the size of the image like maximum it should be 2mb. We are using ng2-file-upload. You can see the code in the bellow:
uploader: FileUploader = new FileUploader({
url: URL,
disableMultipart: true
});
...
...
OnFileSelected(event) {
const file: File = event[0];
this.ReadAsBase64(file)
.then(result => {
this.selectedFile = result;
})
.catch(err => console.log(err));
}
Upload() {
if (this.selectedFile) {
this.usersService.AddImage(this.selectedFile).subscribe(
data => {
this.socket.emit('refresh', {});
console.log(data);
},
err => console.log(err)
);
}
}
ReadAsBase64(file): Promise<any> {
const reader = new FileReader();
const fileValue = new Promise((resolve, reject) => {
reader.addEventListener('load', () => {
resolve(reader.result);
});
reader.addEventListener('error', event => {
reject(event);
});
reader.readAsDataURL(file);
});
return fileValue;
}
Where and how can we set that limit on the image?
According to W3 documentation:
On getting, if the readAsDataURL() read method is used, the result attribute must return a DOMString that is a Data URL [RFC2397] encoding of the File or Blob's data.
So your reader.result
is either null or a DOMString. A DOMString is string with 16-bit characters.
So, to do size check, you should:
Check if reader.result
is null, if it is, then throw an error or reject the Promise
Check the length of your string, knowing that every character is 2 bytes
Throw an error if the length*2 is more than 2^20, in fact 2*2^20 is how many bytes there are in 2MB
Now let's translate it in code:
ReadAsBase64(file): Promise<any> {
const reader = new FileReader();
const fileValue = new Promise((resolve, reject) => {
reader.addEventListener('load', () => {
const result = reader.result as DOMString;
if (!result) reject('Cannot read variable');
if (result.length * 2 > 2**21) reject('File exceeds the maximum size'); // Note: 2*2**20 = 2**21
resolve(reader.result);
});
reader.addEventListener('error', event => {
reject(event);
});
reader.readAsDataURL(file);
});
return fileValue;
}