'Unhandled Rejection (Error): The file given is not an image
here i am upload a file using formik in react js
When the file is upload it's size validation works but type validation not work
Here is my code If anyone can help me so it's really helpful to me
const SUPPORTED_FORMATS = ["image/jpg", "image/jpeg","image/png"]; const onFileChange = async (file) => { const options = {maxSizeMB: 1, maxWidthOrHeight: 500, useWebWorker: true} const compressedFile =await imageCompression(file, options) console.log(`------- Compressed File Size ${compressedFile.size / 1024} KB -------`) var formData = new FormData() formData.append('file', compressedFile) var url = URL.BASE + URL.STORAGE_UPLOAD + 'profileImage' var result = await post(url, formData, 'multipart/form-data') if (result.is_success === false) { addNotification(result.error_message, 'danger'); } else{ var url= reader.readAsDataURL(file) reader.readAsDataURL(file) reader.onloadend = function (e) { setSelectedImgUrl(reader.result); setProfileImage(result.data.fileName); } .bind(this) } } profileImgUrl: Yup .mixed() .nullable() .notRequired() .test( "filesize", requiredMessages.file_size_validation, (file) => !file || (file && file.size <= 2000000) ) .test( "fileformat", requiredMessages.file_type_validation, (file) => !file || (file && SUPPORTED_FORMATS.includes(file.type)) ), <input className="fileInput hidden" type="file" name="profileImgUrl" id="profileImgUrl" accept="image/* onBlur={handleBlur} onChange={(event) => { setFieldValue("profileImgUrl",event.target.files[0])onFileChange(event.target.files[0])}}/>`
Solution 1:[1]
You set the Max Size on the options declaration. You did not set the allowed Types.
const options = {maxSizeMB: 1, maxWidthOrHeight: 500, useWebWorker: true}
Try this (would double check if it's .jpg or jpg as I can't recall the syntax):
const filesFormats = [".jpg", ".gif"];
const isRightFormat = filesFormats.includes(file.type);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mason Stedman |
