原因
telegraph image的默认设置sendPhoto会使png图片的透明底变成白底,经发现是因为telegram的上传会默认压缩图片。
解决思路
参考telegram上传可以选择不压缩上传,后果就是无法在线预览只能下载下来预览,不过我也不需要telegram预览,所以无所谓。
方法是找到upload.js,把里面的上传方式检测image、audio等直接替换成不检测直接以文件形式sendDocument上传,但是得把信息保存到kv不然会报500,以及最后注释掉image、audio等返回结果。
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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| 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; 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'); }
if (env.img_url) { await env.img_url.put(`${fileId}.${fileExtension}`, "", { metadata: { TimeStamp: Date.now(), ListType: "None", Label: "None", liked: false, fileName: fileName, fileSize: uploadFile.size, } }); }
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.document) return result.document.file_id;
return null; }
|