forked from cf-pages/Telegraph-Image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.js
93 lines (74 loc) · 2.72 KB
/
upload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { errorHandling, telemetryData } from "./utils/middleware";
export async function onRequestPost(context) {
const { request, env } = context;
try {
const clonedRequest = request.clone();
const formData = await clonedRequest.formData();
await errorHandling(context);
telemetryData(context);
const uploadFile = formData.get('file');
if (!uploadFile) {
throw new Error('No file uploaded');
}
const fileName = uploadFile.name;
const fileExtension = fileName.split('.').pop().toLowerCase();
const telegramFormData = new FormData();
telegramFormData.append("chat_id", env.TG_Chat_ID);
// 根据文件类型选择合适的上传方式
let apiEndpoint;
if (uploadFile.type.startsWith('image/')) {
telegramFormData.append("photo", uploadFile);
apiEndpoint = 'sendPhoto';
} else {
telegramFormData.append("document", uploadFile);
apiEndpoint = 'sendDocument';
}
const apiUrl = `https://api.telegram.org/bot${env.TG_Bot_Token}/${apiEndpoint}`;
console.log('Sending request to:', apiUrl);
const response = await fetch(
apiUrl,
{
method: "POST",
body: telegramFormData
}
);
console.log('Response status:', response.status);
const responseData = await response.json();
if (!response.ok) {
console.error('Error response from Telegram API:', responseData);
throw new Error(responseData.description || 'Upload to Telegram failed');
}
const fileId = getFileId(responseData);
if (!fileId) {
throw new Error('Failed to get file ID');
}
return new Response(
JSON.stringify([{ 'src': `/file/${fileId}.${fileExtension}` }]),
{
status: 200,
headers: { 'Content-Type': 'application/json' }
}
);
} catch (error) {
console.error('Upload error:', error);
return new Response(
JSON.stringify({ error: error.message }),
{
status: 500,
headers: { 'Content-Type': 'application/json' }
}
);
}
}
function getFileId(response) {
if (!response.ok || !response.result) return null;
const result = response.result;
if (result.photo) {
return result.photo.reduce((prev, current) =>
(prev.file_size > current.file_size) ? prev : current
).file_id;
}
if (result.document) return result.document.file_id;
if (result.video) return result.video.file_id;
return null;
}