mirror of
https://github.com/bitsocialnet/5chan.git
synced 2026-08-03 07:41:04 +02:00
feat: add shared cross-platform catbox media upload flow
Added `useFileUpload()` and `uploadToCatbox()` to centralize upload behavior and remove duplicated upload code from `post-form.tsx` and `reply-modal.tsx`. The flow now routes Android to `FileUploader`, Electron to hidden-input + catbox upload, and web to a translated fallback alert with consistent upload UI state.
This commit is contained in:
@@ -15,13 +15,10 @@ import useFetchGifFirstFrame from '../../hooks/use-fetch-gif-first-frame';
|
||||
import useIsSubplebbitOffline from '../../hooks/use-is-subplebbit-offline';
|
||||
import usePublishPost from '../../hooks/use-publish-post';
|
||||
import usePublishReply from '../../hooks/use-publish-reply';
|
||||
import FileUploader from '../../plugins/file-uploader';
|
||||
import { useFileUpload } from '../../hooks/use-file-upload';
|
||||
import styles from './post-form.module.css';
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { capitalize, debounce } from 'lodash';
|
||||
|
||||
const isAndroid = Capacitor.getPlatform() === 'android';
|
||||
|
||||
// Separate component for offline alert to isolate rerenders from updatingState
|
||||
// Only this component will rerender when updatingState changes, not the whole PostForm
|
||||
const OfflineAlert = ({ subplebbitAddress }: { subplebbitAddress: string | undefined }) => {
|
||||
@@ -197,35 +194,17 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
|
||||
}
|
||||
}, [replyIndex, resetPublishReplyOptions, closeForm]);
|
||||
|
||||
// on android, auto upload file to image hosting sites with open api
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadedFileName, setUploadedFileName] = useState<string | null>(null);
|
||||
const handleUpload = async () => {
|
||||
try {
|
||||
setIsUploading(true);
|
||||
const result = await FileUploader.pickAndUploadMedia();
|
||||
console.log('Upload result:', result);
|
||||
if (result.url) {
|
||||
setUrl(result.url);
|
||||
const { isUploading, uploadedFileName, handleUpload } = useFileUpload({
|
||||
onUploadComplete: (uploadedUrl: string) => {
|
||||
if (uploadedUrl) {
|
||||
setUrl(uploadedUrl);
|
||||
if (urlRef.current) {
|
||||
urlRef.current.value = result.url;
|
||||
}
|
||||
isInPostView ? setPublishReplyOptions({ link: result.url || undefined }) : setPublishPostOptions({ link: result.url || undefined });
|
||||
if (result.fileName) {
|
||||
setUploadedFileName(result.fileName);
|
||||
urlRef.current.value = uploadedUrl;
|
||||
}
|
||||
isInPostView ? setPublishReplyOptions({ link: uploadedUrl }) : setPublishPostOptions({ link: uploadedUrl });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Upload failed:', error);
|
||||
if (error instanceof Error && error.message !== 'File selection cancelled') {
|
||||
alert(`${t('upload_failed')}: ${error.message}`);
|
||||
} else if (typeof error === 'string' && error !== 'File selection cancelled') {
|
||||
alert(`${t('upload_failed')}: ${error}`);
|
||||
}
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const hasInitializedDisplayName = useRef(false);
|
||||
useEffect(() => {
|
||||
@@ -306,17 +285,15 @@ const PostFormTable = ({ closeForm, postCid }: { closeForm: () => void; postCid:
|
||||
<span className={styles.linkType}> {url && <LinkTypePreviewer link={url} />}</span>
|
||||
</td>
|
||||
</tr>
|
||||
{isAndroid && (
|
||||
<tr className={styles.uploadButton}>
|
||||
<td>{t('file')}</td>
|
||||
<td>
|
||||
<button onClick={handleUpload} disabled={isUploading}>
|
||||
{isUploading ? t('uploading') : t('choose_file')}
|
||||
</button>
|
||||
<span>{uploadedFileName ? uploadedFileName : t('no_file_chosen')}</span>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
<tr className={styles.uploadButton}>
|
||||
<td>{t('file')}</td>
|
||||
<td>
|
||||
<button onClick={handleUpload} disabled={isUploading}>
|
||||
{t('choose_file')}
|
||||
</button>
|
||||
<span>{isUploading ? t('uploading') : uploadedFileName || t('no_file_chosen')}</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr className={styles.spoilerButton}>
|
||||
<td>{t('options')}</td>
|
||||
<td>
|
||||
|
||||
@@ -11,16 +11,13 @@ import useSelectedTextStore from '../../stores/use-selected-text-store';
|
||||
import useReplyModalStore from '../../stores/use-reply-modal-store';
|
||||
import usePublishReply from '../../hooks/use-publish-reply';
|
||||
import useIsMobile from '../../hooks/use-is-mobile';
|
||||
import { useFileUpload } from '../../hooks/use-file-upload';
|
||||
import styles from './reply-modal.module.css';
|
||||
import { LinkTypePreviewer } from '../post-form';
|
||||
import { capitalize, debounce } from 'lodash';
|
||||
import FileUploader from '../../plugins/file-uploader';
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { useSpring, animated } from '@react-spring/web';
|
||||
import { useDrag } from '@use-gesture/react';
|
||||
|
||||
const isAndroid = Capacitor.getPlatform() === 'android';
|
||||
|
||||
interface ReplyModalProps {
|
||||
closeModal: () => void;
|
||||
showReplyModal: boolean;
|
||||
@@ -263,35 +260,17 @@ const ReplyModal = ({ closeModal, showReplyModal, parentCid, parentNumber, threa
|
||||
checkContentLength(formattedContent, t);
|
||||
}, [showReplyModal, quoteInsertRequestId, quoteInsertNumber, quoteInsertSelectedText, setPublishReplyOptions, checkContentLength, t]);
|
||||
|
||||
// on android, auto upload file to image hosting sites with open api
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadedFileName, setUploadedFileName] = useState<string | null>(null);
|
||||
const handleUpload = async () => {
|
||||
try {
|
||||
setIsUploading(true);
|
||||
const result = await FileUploader.pickAndUploadMedia();
|
||||
console.log('Upload result:', result);
|
||||
if (result.url) {
|
||||
setUrl(result.url);
|
||||
const { isUploading, uploadedFileName, handleUpload } = useFileUpload({
|
||||
onUploadComplete: (uploadedUrl: string) => {
|
||||
if (uploadedUrl) {
|
||||
setUrl(uploadedUrl);
|
||||
if (urlRef.current) {
|
||||
urlRef.current.value = result.url;
|
||||
}
|
||||
setPublishReplyOptions({ link: result.url || undefined });
|
||||
if (result.fileName) {
|
||||
setUploadedFileName(result.fileName);
|
||||
urlRef.current.value = uploadedUrl;
|
||||
}
|
||||
setPublishReplyOptions({ link: uploadedUrl });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Upload failed, ', error);
|
||||
if (error instanceof Error && error.message !== 'File selection cancelled') {
|
||||
setError(`${t('upload_failed')}, ${error.message}`);
|
||||
} else if (typeof error === 'string' && error !== 'File selection cancelled') {
|
||||
setError(`${t('upload_failed')}, ${error}`);
|
||||
}
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const hasInitializedDisplayName = useRef(false);
|
||||
useEffect(() => {
|
||||
@@ -339,6 +318,7 @@ const ReplyModal = ({ closeModal, showReplyModal, parentCid, parentNumber, threa
|
||||
type='text'
|
||||
ref={urlRef}
|
||||
placeholder={capitalize(t('link'))}
|
||||
disabled={isUploading}
|
||||
onChange={(e) => {
|
||||
setUrl(e.target.value);
|
||||
setPublishReplyOptions({ link: e.target.value });
|
||||
@@ -365,23 +345,21 @@ const ReplyModal = ({ closeModal, showReplyModal, parentCid, parentNumber, threa
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.footer}>
|
||||
{url && !isAndroid && (
|
||||
{url && (
|
||||
<>
|
||||
{t('link_type')}: <LinkTypePreviewer link={url} />
|
||||
</>
|
||||
)}
|
||||
{isAndroid && (
|
||||
<span className={styles.uploadContainer}>
|
||||
<span className={styles.uploadButton}>
|
||||
<button onClick={handleUpload} disabled={isUploading}>
|
||||
{isUploading ? t('uploading') : t('choose_file')}
|
||||
</button>
|
||||
</span>
|
||||
<span className={styles.uploadFileName} title={uploadedFileName ? uploadedFileName : t('no_file_chosen')}>
|
||||
{uploadedFileName ? uploadedFileName : t('no_file_chosen')}
|
||||
</span>
|
||||
<span className={styles.uploadContainer}>
|
||||
<span className={styles.uploadButton}>
|
||||
<button onClick={handleUpload} disabled={isUploading}>
|
||||
{t('choose_file')}
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.uploadFileName} title={uploadedFileName || t('no_file_chosen')}>
|
||||
{isUploading ? t('uploading') : uploadedFileName || t('no_file_chosen')}
|
||||
</span>
|
||||
</span>
|
||||
<span className={styles.spoilerButton}>
|
||||
[
|
||||
<label>
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import * as React from 'react';
|
||||
import { createElement } from 'react';
|
||||
import { createRoot, Root } from 'react-dom/client';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import FileUploader from '../../plugins/file-uploader';
|
||||
import { uploadToCatbox } from '../../lib/utils/catbox-utils';
|
||||
import { useFileUpload } from '../use-file-upload';
|
||||
|
||||
// Enable React's act environment for hook state updates in tests.
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const act = (React as any).act as (callback: () => void | Promise<void>) => void | Promise<void>;
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock('@capacitor/core', () => ({
|
||||
Capacitor: { getPlatform: vi.fn(() => 'web') },
|
||||
}));
|
||||
|
||||
vi.mock('../../plugins/file-uploader', () => ({
|
||||
default: { pickAndUploadMedia: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/utils/catbox-utils', () => ({
|
||||
uploadToCatbox: vi.fn(),
|
||||
}));
|
||||
|
||||
type HookSnapshot = ReturnType<typeof useFileUpload>;
|
||||
|
||||
let latestHook: HookSnapshot | null = null;
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
const HookHarness = ({ onUploadComplete }: { onUploadComplete: (url: string, fileName: string) => void }) => {
|
||||
latestHook = useFileUpload({ onUploadComplete });
|
||||
return null;
|
||||
};
|
||||
|
||||
const getHook = (): HookSnapshot => {
|
||||
if (!latestHook) {
|
||||
throw new Error('Hook is not mounted');
|
||||
}
|
||||
return latestHook;
|
||||
};
|
||||
|
||||
const mountHook = (onUploadComplete = vi.fn()) => {
|
||||
act(() => {
|
||||
root.render(createElement(HookHarness, { onUploadComplete }));
|
||||
});
|
||||
return { onUploadComplete, hook: getHook };
|
||||
};
|
||||
|
||||
const selectFileFromHiddenInput = async (file: File | null) => {
|
||||
const picker = document.querySelector('input[type="file"]') as HTMLInputElement | null;
|
||||
expect(picker).not.toBeNull();
|
||||
Object.defineProperty(picker as HTMLInputElement, 'files', {
|
||||
configurable: true,
|
||||
value: file ? [file] : [],
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
picker?.dispatchEvent(new Event('change'));
|
||||
});
|
||||
};
|
||||
|
||||
describe('useFileUpload', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
latestHook = null;
|
||||
container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('web');
|
||||
window.electronApi = undefined;
|
||||
vi.spyOn(window, 'alert').mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
container.remove();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('uploads via Android plugin and updates state', async () => {
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('android');
|
||||
vi.mocked(FileUploader.pickAndUploadMedia).mockResolvedValue({
|
||||
url: 'https://files.catbox.moe/android.jpg',
|
||||
fileName: 'android.jpg',
|
||||
});
|
||||
|
||||
const { onUploadComplete, hook } = mountHook();
|
||||
|
||||
await act(async () => {
|
||||
await hook().handleUpload();
|
||||
});
|
||||
|
||||
expect(FileUploader.pickAndUploadMedia).toHaveBeenCalledOnce();
|
||||
expect(onUploadComplete).toHaveBeenCalledWith('https://files.catbox.moe/android.jpg', 'android.jpg');
|
||||
expect(hook().uploadedFileName).toBe('android.jpg');
|
||||
expect(hook().isUploading).toBe(false);
|
||||
});
|
||||
|
||||
it('uploads via Electron file picker + catbox utility', async () => {
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
|
||||
window.electronApi = { isElectron: true } as any;
|
||||
vi.mocked(uploadToCatbox).mockResolvedValue('https://files.catbox.moe/electron.png');
|
||||
|
||||
const selectedFile = new File(['abc'], 'electron.png', { type: 'image/png' });
|
||||
const { onUploadComplete, hook } = mountHook();
|
||||
|
||||
let uploadPromise: Promise<void> | undefined;
|
||||
await act(async () => {
|
||||
uploadPromise = hook().handleUpload();
|
||||
});
|
||||
await selectFileFromHiddenInput(selectedFile);
|
||||
await act(async () => {
|
||||
await uploadPromise;
|
||||
});
|
||||
|
||||
expect(uploadToCatbox).toHaveBeenCalledWith(selectedFile);
|
||||
expect(onUploadComplete).toHaveBeenCalledWith('https://files.catbox.moe/electron.png', 'electron.png');
|
||||
expect(hook().uploadedFileName).toBe('electron.png');
|
||||
expect(hook().isUploading).toBe(false);
|
||||
});
|
||||
|
||||
it('shows web fallback alert and does not upload', async () => {
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('web');
|
||||
window.electronApi = undefined;
|
||||
const { onUploadComplete, hook } = mountHook();
|
||||
|
||||
await act(async () => {
|
||||
await hook().handleUpload();
|
||||
});
|
||||
|
||||
expect(window.alert).toHaveBeenCalledWith('upload_not_supported_web');
|
||||
expect(uploadToCatbox).not.toHaveBeenCalled();
|
||||
expect(FileUploader.pickAndUploadMedia).not.toHaveBeenCalled();
|
||||
expect(onUploadComplete).not.toHaveBeenCalled();
|
||||
expect(hook().isUploading).toBe(false);
|
||||
});
|
||||
|
||||
it('silently ignores file selection cancellation', async () => {
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
|
||||
window.electronApi = { isElectron: true } as any;
|
||||
const { onUploadComplete, hook } = mountHook();
|
||||
|
||||
let uploadPromise: Promise<void> | undefined;
|
||||
await act(async () => {
|
||||
uploadPromise = hook().handleUpload();
|
||||
});
|
||||
await selectFileFromHiddenInput(null);
|
||||
await act(async () => {
|
||||
await uploadPromise;
|
||||
});
|
||||
|
||||
expect(uploadToCatbox).not.toHaveBeenCalled();
|
||||
expect(window.alert).not.toHaveBeenCalled();
|
||||
expect(onUploadComplete).not.toHaveBeenCalled();
|
||||
expect(hook().isUploading).toBe(false);
|
||||
});
|
||||
|
||||
it('alerts on upload failure and resets uploading state', async () => {
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('android');
|
||||
vi.mocked(FileUploader.pickAndUploadMedia).mockRejectedValue(new Error('boom'));
|
||||
const { onUploadComplete, hook } = mountHook();
|
||||
|
||||
await act(async () => {
|
||||
await hook().handleUpload();
|
||||
});
|
||||
|
||||
expect(window.alert).toHaveBeenCalledWith('upload_failed: boom');
|
||||
expect(onUploadComplete).not.toHaveBeenCalled();
|
||||
expect(hook().isUploading).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import FileUploader from '../plugins/file-uploader';
|
||||
import { uploadToCatbox } from '../lib/utils/catbox-utils';
|
||||
|
||||
const FILE_SELECTION_CANCELLED_ERROR = 'File selection cancelled';
|
||||
|
||||
export interface UseFileUploadOptions {
|
||||
onUploadComplete: (url: string, fileName: string) => void;
|
||||
}
|
||||
|
||||
function selectFileViaInput(): Promise<File | null> {
|
||||
return new Promise((resolve) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,video/mp4,video/webm';
|
||||
input.style.display = 'none';
|
||||
|
||||
const cleanup = () => {
|
||||
input.remove();
|
||||
window.removeEventListener('focus', onFocus);
|
||||
};
|
||||
|
||||
const onFocus = () => {
|
||||
window.removeEventListener('focus', onFocus);
|
||||
setTimeout(() => {
|
||||
if (input.files && input.files.length > 0) {
|
||||
return;
|
||||
}
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
input.addEventListener('change', () => {
|
||||
window.removeEventListener('focus', onFocus);
|
||||
if (input.files && input.files.length > 0) {
|
||||
const file = input.files[0];
|
||||
cleanup();
|
||||
resolve(file);
|
||||
} else {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('focus', onFocus);
|
||||
document.body.appendChild(input);
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
export function useFileUpload(options: UseFileUploadOptions) {
|
||||
const { t } = useTranslation();
|
||||
const { onUploadComplete } = options;
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadedFileName, setUploadedFileName] = useState<string | null>(null);
|
||||
|
||||
const handleUpload = useCallback(async () => {
|
||||
try {
|
||||
setIsUploading(true);
|
||||
setUploadedFileName(null);
|
||||
|
||||
if (Capacitor.getPlatform() === 'android') {
|
||||
const result = await FileUploader.pickAndUploadMedia();
|
||||
if (result.url) {
|
||||
if (result.fileName) {
|
||||
setUploadedFileName(result.fileName);
|
||||
}
|
||||
onUploadComplete(result.url, result.fileName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.electronApi?.isElectron) {
|
||||
const file = await selectFileViaInput();
|
||||
if (!file) {
|
||||
throw new Error(FILE_SELECTION_CANCELLED_ERROR);
|
||||
}
|
||||
|
||||
const url = await uploadToCatbox(file);
|
||||
setUploadedFileName(file.name);
|
||||
onUploadComplete(url, file.name);
|
||||
return;
|
||||
}
|
||||
|
||||
window.alert(t('upload_not_supported_web'));
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
if (errorMessage !== FILE_SELECTION_CANCELLED_ERROR) {
|
||||
window.alert(`${t('upload_failed')}: ${errorMessage}`);
|
||||
}
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
}, [onUploadComplete, t]);
|
||||
|
||||
return {
|
||||
isUploading,
|
||||
uploadedFileName,
|
||||
handleUpload,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { uploadToCatbox } from '../catbox-utils';
|
||||
|
||||
describe('uploadToCatbox', () => {
|
||||
const originalFetch = global.fetch;
|
||||
beforeEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it('POSTs file to catbox API and returns trimmed URL', async () => {
|
||||
const mockFile = new File(['content'], 'test.png', { type: 'image/png' });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
text: () => Promise.resolve(' https://files.catbox.moe/abc123.png '),
|
||||
}),
|
||||
);
|
||||
|
||||
const url = await uploadToCatbox(mockFile);
|
||||
expect(url).toBe('https://files.catbox.moe/abc123.png');
|
||||
|
||||
const call = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(call[0]).toBe('https://catbox.moe/user/api.php');
|
||||
expect(call[1]?.method).toBe('POST');
|
||||
const body = call[1]?.body as FormData;
|
||||
expect(body.get('reqtype')).toBe('fileupload');
|
||||
expect(body.get('fileToUpload')).toBe(mockFile);
|
||||
});
|
||||
|
||||
it('throws Error on non-ok response', async () => {
|
||||
const mockFile = new File(['x'], 'x.txt', { type: 'text/plain' });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(uploadToCatbox(mockFile)).rejects.toThrow('Upload failed: 500 Internal Server Error');
|
||||
});
|
||||
|
||||
it('throws when fetch rejects with a network error', async () => {
|
||||
const mockFile = new File(['x'], 'x.txt', { type: 'text/plain' });
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network down')));
|
||||
|
||||
await expect(uploadToCatbox(mockFile)).rejects.toThrow('Network down');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
const CATBOX_API = 'https://catbox.moe/user/api.php';
|
||||
|
||||
/**
|
||||
* Upload a file to catbox.moe.
|
||||
* @param file - The file to upload
|
||||
* @returns The URL of the uploaded file
|
||||
* @throws Error when the response is not ok
|
||||
*/
|
||||
export async function uploadToCatbox(file: File): Promise<string> {
|
||||
const formData = new FormData();
|
||||
formData.append('reqtype', 'fileupload');
|
||||
formData.append('fileToUpload', file);
|
||||
|
||||
const response = await fetch(CATBOX_API, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
return text.trim();
|
||||
}
|
||||
Reference in New Issue
Block a user