Skip to content

Commit

Permalink
fix: pdf preview base64 too large to preview (#1031)
Browse files Browse the repository at this point in the history
  • Loading branch information
caoxing9 authored Oct 28, 2024
1 parent 35dc171 commit f64c4cb
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 29 deletions.
2 changes: 1 addition & 1 deletion apps/nextjs-app/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const secureHeaders = createSecureHeaders({
'https://*.teable.io',
'https://*.teable.cn',
],
frameSrc: ["'self'", 'data:'],
frameSrc: ["'self'", 'blob:'],
connectSrc: [
"'self'",
'https://*.sentry.io',
Expand Down
12 changes: 6 additions & 6 deletions packages/ui-lib/src/base/file/preview/pdf/PDFPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@ import React, { useState, useEffect } from 'react';
import { Skeleton } from '../../../../shadcn';
import { Spin } from '../../../spin/Spin';
import type { IFileItemInner } from '../FilePreviewContext';
import { urlToBase64 } from './utils';
import { getBlobUrlFromUrl } from './utils';

interface IPdfPreviewProps extends IFileItemInner {}

export const PDFPreview = (props: IPdfPreviewProps) => {
const [base64, setBase64] = useState('');
const [blobUrl, setBlobUrl] = useState('');

useEffect(() => {
urlToBase64(props.src).then((res) => {
setBase64(res.base64WithPrefix);
getBlobUrlFromUrl(props.src).then((res) => {
setBlobUrl(res);
});
}, [props.src]);

return base64 ? (
return blobUrl ? (
<iframe
src={base64}
src={blobUrl}
width="100%"
height="100%"
title="PDF Viewer"
Expand Down
26 changes: 4 additions & 22 deletions packages/ui-lib/src/base/file/preview/pdf/utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,6 @@
export const urlToBase64 = async (
url: string
): Promise<{ base64: string; base64WithPrefix: string }> => {
try {
const response = await fetch(url);
const blob = await response.blob();
import { getBlobFromUrl } from '../office/utils';

return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = String(reader.result);
base64String &&
resolve({
base64: base64String.split(',')[1],
base64WithPrefix: base64String,
});
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (error) {
throw new Error(`Failed to convert URL to base64: ${(error as Error)?.message}`);
}
export const getBlobUrlFromUrl = async (url: string) => {
const blob = await getBlobFromUrl(url);
return URL.createObjectURL(blob);
};

0 comments on commit f64c4cb

Please sign in to comment.