Skip to content

Commit

Permalink
fix: SVG Upload Preview Error (ant-design#36402)
Browse files Browse the repository at this point in the history
* Update utils.tsx

* style: unify img styling

Unify the styling  of img attribute setting.

* test: add previewImage test for svg file

Add previewImage test for SVG upload

* fix: remove charset

Remove charset in data url for text content.

* test: fix test

* fix: typo

* fix: correct patching for svg upload error

* fix: correct patching for svg upload error

* test: update test
  • Loading branch information
jonioni authored Jul 14, 2022
1 parent e9ab30d commit 92c8bdc
Showing 2 changed files with 39 additions and 1 deletion.
29 changes: 29 additions & 0 deletions components/upload/__tests__/uploadlist.test.js
Original file line number Diff line number Diff line change
@@ -928,6 +928,35 @@ describe('Upload List', () => {
unmount();
});

it('upload svg file with <foreignObject> should not have CORS error', async () => {
const mockFile = new File(
[
'<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"><foreignObject x="20" y="20" width="160" height="160"><div xmlns="http://www.w3.org/1999/xhtml">Test</div></foreignObject></svg>',
],
'bar.svg',
{ type: 'image/svg+xml' },
);

const previewFunc = jest.fn(previewImage);

const { unmount } = render(
<Upload
fileList={[{ originFileObj: mockFile }]}
previewFile={previewFunc}
locale={{ uploading: 'uploading' }}
listType="picture-card"
/>,
);

await waitFor(() => {
expect(previewFunc).toHaveBeenCalled();
});
await previewFunc(mockFile).then(dataUrl => {
expect(dataUrl).toEqual('data:image/png;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',
11 changes: 10 additions & 1 deletion components/upload/utils.tsx
Original file line number Diff line number Diff line change
@@ -110,6 +110,15 @@ export function previewImage(file: File | Blob): Promise<string> {

resolve(dataURL);
};
img.src = window.URL.createObjectURL(file);
img.crossOrigin = "anonymous";
if (file.type.startsWith("image/svg+xml")) {
const reader = new FileReader();
reader.addEventListener('load', () => {
if (reader.result) img.src = reader.result as string;
});
reader.readAsDataURL(file);
} else {
img.src = window.URL.createObjectURL(file);
}
});
}

0 comments on commit 92c8bdc

Please sign in to comment.