사진을 압축할 수있는 라이브러리이다.
onchange
핸들러를 씌우면 된다.async function handleImageUpload(event) {
const imageFile = event.target.files[0];
console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);
const options = {
maxSizeMB: 1,
maxWidthOrHeight: 1920,
useWebWorker: true
}
try {
const compressedFile = await imageCompression(imageFile, options);
console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
await uploadToServer(compressedFile); // write your own logic
} catch (error) {
console.log(error);
}
}
이를 util 함수로 만들어 보자.
interface CompressImgProps {
file: File;
fileName: string;
fileType?: string;
setImage?: (image: string) => void;
setFile?: (file: File) => void;
}
export const compressImg = async ({
file,
fileName,
fileType = 'image/jpeg',
setFile = () => {},
setImage = () => {},
}: CompressImgProps) => {
const options = {
maxSizeMB: 0.2,
maxWidthOrHeight: 1920,
useWebWorker: true,
};
try {
const compressionFile = await imageCompression(file, options);
const reader = new FileReader();
reader.onload = () => {
setImage(reader.result as string);
};
reader.readAsDataURL(compressionFile);
const blob = compressionFile.slice(0, compressionFile.size, fileType);
setFile(
new File([blob], `${fileName}`, {
type: compressionFile.type,
}),
);
} catch (error) {
alert(error);
}
};
const onAddFiles = async (newFile: File) => {
setLoadingImage(true);
await $$.compressImg({
file: newFile,
fileName: `${storeId}.jpg`,
setImage,
setFile,
});
setLoadingImage(false);
};
export const upload_store_image = ({
file,
str_id,
}: {
file: File;
str_id: number;
}) => {
const formData = new FormData();
formData.append('image', file);
return onAxios<{ key: string; url: string }>({
url: `${route}/${str_id}/images`,
method: 'POST',
data: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
});
};