Почему не работает создание файла из blob?
Вложений: 1
Подскажите пожалуйста где проблема, уже понятия не имею почему не работает. Должно работать так что обрезается фото, и отправляется на сервер как файл. Для этого я создавал canvas, из него blob и уже из него файл, но получается всё не то. (Back-end ожидает от меня только файл, base64 отправить ему я не могу....)
вот код https://codesandbox.io/s/vibrant-haw...seCropImage.ts import { useCallback, useEffect, useRef, useState, ChangeEvent } from "react"; import { Crop } from "react-image-crop"; export const useCropImage = ( width: number, height: number, minWidth = 250, minHeight = 250 ) => { const imgRef = useRef<any>(null); const [crop, setCrop] = useState<Crop>({ unit: "px", x: 130, y: 36, width: width < minWidth ? minWidth : width, height: height < minHeight ? minHeight : height }); const [image, setImage] = useState<any>(); const [imageSrc, setImageSrc] = useState<any>(); const [nameFile, setNameFile] = useState(""); const onSelectFile = (evt: ChangeEvent<HTMLInputElement>) => { if (evt.target.files && evt.target.files.length > 0) { const reader = new FileReader(); reader.readAsDataURL(evt.target.files[0]); setNameFile(evt.target.files[0].name.replace(" ", "")); reader.addEventListener("load", () => setImageSrc(reader.result)); } }; const onLoad = useCallback((evt: any) => setImage(evt.target), []); function blobToFile(theBlob: Blob, fileName: string) { return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type }); } const cropImageNow = () => { if (!image) { return; } const canvas = document.createElement("canvas"); const scaleX = image.naturalWidth / image.width; const scaleY = image.naturalHeight / image.height; canvas.width = crop.width; canvas.height = crop.height; const ctx = canvas.getContext("2d"); if (ctx) { const pixelRatio = window.devicePixelRatio; canvas.width = crop.width * pixelRatio; canvas.height = crop.height * pixelRatio; ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); ctx.imageSmoothingQuality = "high"; ctx.drawImage( image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width, crop.height ); } canvas.toBlob((blob) => { console.log(blob); const formData = new FormData(); formData.append("image", blob, "image.png"); console.log([...formData.entries()]); }, "image/png"); }; return { crop, imgRef, onLoad, setCrop, imageSrc, nameFile, minWidth, minHeight, setImageSrc, cropImageNow, onSelectFile }; }; Вот такое сейчас получаю (фото) https://ibb.co/VDzH0w9 Вложение 4836 |
Часовой пояс GMT +3, время: 15:24. |