I am creating a canvas to rotate an image and creating a blob. But I need it as a file to upload it to server.
return new Promise((resolve, reject) => {
canvas.toBlob(blob => {
// returning an error
if (!blob) {
reject(new Error('Canvas is empty'));
return;
}
// blob.name = fileName;
// creating a Object URL representing the Blob object given
const rotatedImageUrl = window.URL.createObjectURL(blob);
resolve(rotatedImageUrl);
}, 'image/jpeg');
});
I am trying to create a file from the blob . I'm able to create it by using this snippet.
const rotatedFile = new File([img], originalFile.name, {
type: originalFile.type,
});
But the problem is generated file size is only 58 byte.
lastModified: 1644577677380
lastModifiedDate: Fri Feb 11 2022 17:07:57 GMT 0600 (Bangladesh Standard Time) {}
name: "IMG_4792.JPG"
size: 58
type: "image/jpeg"
webkitRelativePath: ""
I think the image is corrupted somehow. Initially I thought canvas is somehow corrupting my image but I have also tried to create a file from an uploaded file converted to blob. That also gave me the same output. File size is not correct.
const file = e.target.files[0];
const blobUrl = URL.createObjectURL(file);
const generatedFile = new File([blobUrl], 'untitled', {
type: file.type,
});
Is there any solution? How can I properly create the file from the blob?
CodePudding user response:
Why are you using the createObjectURL
?
You should resolve the blob
directly resolve(blob);
and then the file will correctly represent the image, instead of representing the objectURL
.
What you are seeing is the length of the generated url. Something like "blob:https://........'