react之Ant Design upload上傳圖片前使用Promise判斷高寬

實現(xiàn)限制圖片上傳格式、尺寸、分辨率的限制

官網(wǎng)API如下:


image.png

實現(xiàn)方式

//checkImageWH  返回一個promise  檢測通過返回resolve  失敗返回reject阻止圖片上傳
    checkImageWH(file, width, height) {
        let self = this;
        return new Promise(function (resolve, reject) {
            let filereader = new FileReader();
            filereader.onload = e => {
                let src = e.target.result;
                const image = new Image();
                image.onload = function () {
                    if (width && this.width != width) {
                        Modal.error({
                            title: '請上傳寬為' + width + '的圖片'
                        })
                        reject();
                    } else if (height && this.height != height) {
                        Modal.error({
                            title: '請上傳高為' + height + '的圖片',
                        })
                        reject();
                    } else {
                        resolve();
                    }
                };
                image.onerror = reject;
                image.src = src;
            };
            filereader.readAsDataURL(file);
        });
    }
    handleBeforeUpload = (file) => {
        //限制圖片 格式、size、分辨率
        const isJPG = file.type === 'image/jpeg';
        // const isJPEG  = file.type === 'image/jpeg';
        const isGIF = file.type === 'image/gif';
        const isPNG = file.type === 'image/png';
        if (!(isJPG || isGIF || isPNG)) {
            Modal.error({
                title: '只能上傳JPG 、JPEG 、GIF、 PNG格式的圖片~'
            })
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            Modal.error({
                title: '超過2M限制 不允許上傳~'
            })
        }
        return (isJPG || isGIF || isPNG ) && isLt2M && this.checkImageWH(file, 1268, 950);
    }
<Upload
                            action={action}
                            data={{project_id: this.props.projectId}}
                            listType="picture-card"
                            fileList={fileList}
                            multiple={true}
                            showUploadList={false}
                            onPreview={this.handlePreview}
                            onChange={this.handleChange}
                            beforeUpload={this.handleBeforeUpload}
                        >
                            {!this.state.locaImagesShow ? null : uploadButton}
                        </Upload>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容