Last active
March 22, 2024 12:24
-
-
Save DeoluA/4d483e9c2054594c44306b601cd8cc30 to your computer and use it in GitHub Desktop.
Ant Design - Check the file type, file size and image dimensions before upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// plugged in this answer from S.O. - https://stackoverflow.com/a/8904008/5172977 | |
// import { Upload } from 'antd'; | |
// function returns a promise | |
beforeUpload = (file) => { | |
return new Promise((resolve, reject) => { | |
// check the file type - you can specify the types you'd like here: | |
const isImg = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/gif'; | |
if (!isImg) { | |
// alert('You can only upload images'); | |
reject(false); | |
}; | |
// check the file size - you can specify the file size you'd like here: | |
const isLt5M = file.size / 1024 / 1024 <= 5; | |
if (!isLt5M) { | |
// alert('Image must smaller than 5MB!'); | |
reject(false); | |
}; | |
// check for dimensions | |
var reader = new FileReader(); | |
// Read the contents of Image File. | |
reader.readAsDataURL(file); | |
reader.onload = (e) => { | |
// Initiate the JavaScript Image object. | |
var image = new Image(); | |
// Set the Base64 string return from FileReader as source. | |
image.src = e.target.result; | |
image.onload = function () { | |
const height = this.height; | |
const width = this.width; | |
// if the aspect ratio is in our sweet spot, proceed - you can specify whatever checks for height and width you want | |
if( (width/height >= 1) ){ | |
resolve(true); | |
} | |
else { | |
// alert('Image does not have optimal dimensions. Please crop or replace.'); | |
reject(false); | |
}; | |
}; | |
}; | |
}); | |
}; | |
// then plug into your Ant Design Upload component | |
/* | |
<Upload | |
beforeUpload={beforeUpload} | |
> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome, thnx