Implement image upload and viewer in v2

This commit is contained in:
LeonspaceX
2026-01-26 21:41:28 +08:00
parent 07bf09949f
commit 0cda40060e
9 changed files with 499 additions and 17 deletions

View File

@@ -290,3 +290,52 @@ export const postComment = async (commentData: PostCommentRequest): Promise<Post
throw error;
}
};
export const uploadImage = async (file: File): Promise<string> => {
try {
const identity_token = await get_id_token();
const formData = new FormData();
formData.append('file', file);
if (identity_token) {
formData.append('identity_token', identity_token);
}
const response = await fetch('/api/upload_pic', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
if (json.code === 1001 && typeof json.data === 'string') {
return json.data;
}
if (json.code === 2006) {
throw new Error('UPLOAD_TOO_LARGE');
}
if (json.code === 2007) {
throw new Error('UNSUPPORTED_FORMAT');
}
throw new Error(json.data || 'Upload failed');
} catch (error) {
console.error('Failed to upload image:', error);
throw error;
}
};
export const getFileName = async (path: string): Promise<string> => {
try {
const response = await fetch(`/api/file_name?path=${encodeURIComponent(path)}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
if (json.code === 1000 && typeof json.data === 'string') {
return json.data;
}
throw new Error('Invalid response code or missing data');
} catch (error) {
console.error('Failed to fetch file name:', error);
throw error;
}
};