fix(Upload): gif thumb url base64 type should be corrected (#44083)

* fix(Upload): gif thumb url base64 type should be corrected

* fix: add revokeObjectURL

* case: update

* case: remove comment

* fix: addEventListener -> onload

---------

Co-authored-by: afc163 <afc163@gmail.com>
This commit is contained in:
daisy 2023-08-09 15:19:25 +08:00 committed by GitHub
parent a48e17717c
commit baa24a6ef9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 3 deletions

View File

@ -35,6 +35,8 @@ describe('Upload List', () => {
// jsdom not support `createObjectURL` yet. Let's handle this.
const originCreateObjectURL = window.URL.createObjectURL;
window.URL.createObjectURL = jest.fn(() => '');
const originRevokeObjectURL = window.URL.revokeObjectURL;
window.URL.revokeObjectURL = jest.fn(() => '');
// Mock dom
let size = { width: 0, height: 0 };
@ -88,6 +90,7 @@ describe('Upload List', () => {
afterAll(() => {
window.URL.createObjectURL = originCreateObjectURL;
window.URL.revokeObjectURL = originRevokeObjectURL;
mockWidthGet.mockRestore();
mockHeightGet.mockRestore();
mockSrcSet.mockRestore();
@ -921,6 +924,31 @@ describe('Upload List', () => {
unmount();
});
it('upload gif file should be converted to the image/gif base64', async () => {
const mockFile = new File([''], 'foo.gif', {
type: 'image/gif',
});
const previewFunc = jest.fn(previewImage);
const { unmount } = render(
<Upload
fileList={[{ originFileObj: mockFile }] as UploadProps['fileList']}
previewFile={previewFunc}
locale={{ uploading: 'uploading' }}
listType="picture-card"
/>,
);
await waitFor(() => {
expect(previewFunc).toHaveBeenCalled();
});
await previewFunc(mockFile).then((dataUrl) => {
expect(dataUrl).toEqual('data:image/gif;base64,');
});
unmount();
});
it("upload non image file shouldn't be converted to the base64", async () => {
const mockFile = new File([''], 'foo.7z', {
type: 'application/x-7z-compressed',

View File

@ -108,15 +108,21 @@ export function previewImage(file: File | Blob): Promise<string> {
ctx!.drawImage(img, offsetX, offsetY, drawWidth, drawHeight);
const dataURL = canvas.toDataURL();
document.body.removeChild(canvas);
window.URL.revokeObjectURL(img.src);
resolve(dataURL);
};
img.crossOrigin = 'anonymous';
if (file.type.startsWith('image/svg+xml')) {
const reader = new FileReader();
reader.addEventListener('load', () => {
reader.onload = () => {
if (reader.result) img.src = reader.result as string;
});
};
reader.readAsDataURL(file);
} else if (file.type.startsWith('image/gif')) {
const reader = new FileReader();
reader.onload = () => {
if (reader.result) resolve(reader.result as string);
};
reader.readAsDataURL(file);
} else {
img.src = window.URL.createObjectURL(file);