antd upload to get file width and height
The new requirements for the project need to determine the width and height of the uploaded image. After checking the antd-upload component, it seems that it does not support this query, so it needs to use an external API.
Directly upload the code: beforeUpload method
handleBeforeUpload = async (file, fileList) => { const {fileMinSize = 0,fileMinWH,fileMaxWH, fileMaxSize = 50,uploadFormat = '',uploadFormatError = ''} = ; const isInRange = (( > (fileMinSize * 1024 * 1024)) && ( < (fileMaxSize * 1024 * 1024))); let isTrueType = true,isFileWH = true;//Type, Size return new Promise((resolve, reject) =>{ //Calibration format if(uploadFormat != ''){ let acceptArr = (','); let fileType = (('.')); if(!(fileType)){ isTrueType = false; ((uploadFormatError == '') ? 'Please upload files within the scope of the rules!' : uploadFormatError); ({'': ()}); } } //Calculate the size if (!isInRange) {//Size identification ((fileMaxSize == 50) ? 'Please upload files within the scope of the rules!' : 'The maximum file cannot be exceeded'+ fileMaxSize + 'M!'); ({'': ()}); } //Calculate width and height /*********************************/ if(fileMinWH && fileMaxWH){//Do filter some pictures that need to be filtered var reader = new FileReader(); (file); = (e) => { //Load the image to get the real width and height of the image var image = new Image(); =; = () =>{ var width = ;//The width of the picture var height = ;//The picture is high if(width < fileMinWH || width > fileMaxWH || height < fileMinWH || height > fileMaxWH){ isFileWH = false; ('***Width and height need to be greater than 600 pixels, less than 4000 pixels'); ({'': []}); reject(); }else{ resolve(isFileWH && isInRange && isTrueType) } }; }; /**********************************/ }else{ resolve(isInRange && isTrueType); } }) };
In this way, this function can be solved perfectly, and the code included is the most important.
antd upload file size limit react Hooks
const uploadImages = { action: requestUrl + '/api/common/CommonUpload', headers: { SessionKey: `${('sk')}`, }, data: (file) => { return { UploadType: 1027,// Backend defined type Id: uuidv4(), FileType: getUploadFileType(file), }; }, beforeUpload: (file) => {// Gift image const limitFileNameLen = 100; return new Promise((resolve, reject) => { if ( && > limitFileNameLen) { ('Please upload a file with a file name less than 100 characters'); //Please upload a file with a file name of no more than 100 characters return (); } const limitM = 2; const isLimit = / 1024 / 1024 <= limitM; (isLimit); if (!isLimit) { ('The size exceeds the limit'); return (); } return resolve(); }); }, }
template:
<Upload {...uploadImages} accept=".jpeg,.png,.jpg" listType="picture-card" fileList={fileList} onChange={handleChange} onPreview={handlePreview} > { >= 4 ? null : uploadButton} </Upload>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.