gpt4 book ai didi

javascript - 限制 react-dropzone 中的图像尺寸

转载 作者:行者123 更新时间:2023-12-05 00:34:28 27 4
gpt4 key购买 nike

我正在使用 react-dropzone 进行图像上传。一切正常。验证图像大小也可以正常工作。但我无法检查图像的尺寸。我想验证图像的宽度和高度,以强制用户在指定的宽度和高度之间上传图像。我试过image.addEventListener('load')但这不起作用。

这是我所做的

export const UploadField = ({ preview, label, uploadProps, ...props }) => {
const {
input: { onChange },
disabled
} = props;

const {
isDragActive,
getRootProps,
getInputProps,
isDragReject,
rejectedFiles
} = useDropzone({
onDrop: files => {
onChange(
files.map(file => {
const image = new Image();
image.addEventListener("load", () => {
console.log("image", image);
});
return Object.assign(file, {
preview: URL.createObjectURL(file)
});
})
);
},
...uploadProps
});

const isFileTooLarge =
rejectedFiles.length > 0 && rejectedFiles[0].size > uploadProps.maxSize;

const files = props.input.value;

if (disabled) {
return null;
}

return (
<>
{label && <Label>{label}</Label>}
<DropzoneContainer {...getRootProps()}>
<input {...getInputProps()} />
{!isDragActive && "Click here or drop a file to upload!"}
{isDragActive && !isDragReject && "Drop it like it's hot!"}
{isDragReject && "File type not accepted, sorry!"}
{isFileTooLarge && (
<div className="text-danger mt-2">File is too large.</div>
)}
</DropzoneContainer>
<div>
{files && files !== undefined ? (
<>
<Preview files={files} isLocal />
</>
) : (
<Preview files={preview} isLocal={false} />
)}
</div>
</>
);
};

export default UploadField;

UploadField.defaultProps = {
uploadProps: {
accept: "image/*",
multiple: false,
minSize: 0,
maxSize: 5242880
}
};

const DropzoneContainer = styled.div`
width: 100%;
padding: 14px;
border-width: 2px;
border-radius: 2px;
border-color: ${props => getColor(props)};
border-style: dashed;
background-color: #fafafa;
color: #bdbdbd;
outline: none;
transition: border 0.24s ease-in-out;
`;

const getColor = props => {
if (props.isDragAccept) {
return "#00e676";
}
if (props.isDragReject) {
return "#ff1744";
}
if (props.isDragActive) {
return "#2196f3";
}
return "#eeeeee";
};

最佳答案

你从来没有设置src对于图像,因此您的事件处理程序永远不会触发。尝试设置image.src = URL.createObjectURL(file) .文件加载后,您的“加载”处理程序将触发。
尝试更改 onDrop 的内容回调包括这个:

const filteredImages = [];
let counter = 0;

files.map(file => {
const image = new Image();
image.addEventListener('load', () => {
console.log(`${image.width}x${image.height}`)

// only select images within width/height limits
if (image.width < WIDTH_LIM && image.height < HEIGHT_LIM) {
filteredImages.push(image)
}

// increment counter for each image we go through
counter += 1;

// if we have gone through all the files, handle the ones that
// made it through the filter using `handleImages` function
if (counter === files.length) handleImages(filteredImages);
});
image.src = URL.createObjectURL(file)
})

关于javascript - 限制 react-dropzone 中的图像尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59761934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com