Skip to content

Commit

Permalink
0.10.11
Browse files Browse the repository at this point in the history
  • Loading branch information
BlueSkyXN committed Nov 5, 2024
1 parent 122d3fb commit 73126c0
Show file tree
Hide file tree
Showing 4 changed files with 252 additions and 1 deletion.
1 change: 1 addition & 0 deletions cloudflare-page/OneAPI-imgbed-MIX.html
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ <h2>File Upload</h2>
<option value="vviptuangou">vviptuangou-国内CDN</option>
<option value="da8m">da8m-国内CDN</option>
<option value="aliex">AliEx-国内CDN国外Akamai-不提供账号请自行部署后端</option>
<option value="mtdp">MTDP</option>
</select>
</div>
<div class="form-check mb-2">
Expand Down
95 changes: 95 additions & 0 deletions cloudflare-worker-js-api/API_IMG_mtdp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
async function handleMtDpRequest(request) {
console.log('Request received for DP upload:', request.url);

if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}

try {
// 解析请求中的表单数据
const formData = await request.formData();
const file = formData.get('image'); // 前端上传的字段名为 'image'

if (!file) {
return new Response('No file uploaded', { status: 400 });
}

// 获取文件信息
const fileName = file.name;
const fileType = file.type; // 如 'image/jpeg'
const fileSize = file.size;

// 生成新的文件名(使用 MD5 和随机数)
const timeStamp = new Date().getTime().toString();
const randomNum = Math.floor(Math.random() * 100000).toString();
const hash = await crypto.subtle.digest('MD5', new TextEncoder().encode(timeStamp + randomNum));
const hashArray = Array.from(new Uint8Array(hash));
const md5Hash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
const newFileName = md5Hash + '.' + fileName.split('.').pop();

// 获取文件的最后修改时间(GMT 格式)
const lastModifiedDate = new Date().toUTCString();

// 创建新的 FormData,用于发送到大众点评的接口
const dpFormData = new FormData();
dpFormData.append('id', 'WU_FILE_0'); // 固定值
dpFormData.append('name', newFileName);
dpFormData.append('type', fileType);
dpFormData.append('lastModifiedDate', lastModifiedDate);
dpFormData.append('size', fileSize);
dpFormData.append('file', file, newFileName); // 文件字段名为 'file'

// 设置必要的头部信息
const dpHeaders = {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};

// 大众点评的上传接口 URL
const dpUrl = 'https://trust.dianping.com/upload.action';

// 发送请求到大众点评接口
const response = await fetch(dpUrl, {
method: 'POST',
headers: dpHeaders,
body: dpFormData
});

if (!response.ok) {
const errorText = await response.text();
console.error(`Upload failed: Status ${response.status}, Body: ${errorText}`);
return new Response(`Upload failed: ${errorText}`, { status: response.status });
}

// 解析大众点评接口的响应
const responseData = await response.json();
console.log('Response from DP API:', responseData);

if (responseData && responseData.isSuccess) {
let url = responseData.url;

// 转为 HTTPS 协议
url = url.replace('http://', 'https://');

// 随机替换域名前缀
const prefixes = ['img', 'p0', 'p1', 'p2'];
const randomPrefix = prefixes[Math.floor(Math.random() * prefixes.length)];
url = url.replace(/\/\/p0\./, `//${randomPrefix}.`);

// 成功,返回图片 URL
return new Response(url, {
status: 200,
headers: {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*' // 根据需要调整 CORS 策略
}
});
} else {
console.error('Upload failed:', responseData);
return new Response('Upload failed', { status: 500 });
}
} catch (error) {
console.error('Error in handleDpUploadRequest:', error);
return new Response('Internal Server Error', { status: 500 });
}
}
102 changes: 101 additions & 1 deletion cloudflare-worker-js-api/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ async function handleRequest(request) {
case '/upload/jdkf':
response = await handlejdkfRequest(request);
break;
case '/upload/mtdp':
response = await handleMtDpRequest(request);
break;
default:
response = new Response('Not Found', { status: 404 });
break;
Expand Down Expand Up @@ -413,7 +416,7 @@ async function handleRequest(request) {

// 构建图片访问链接
//const accessUrl = `https://cdn.img2ipfs.com/ipfs/${fileHash}?filename=${fileName}`;
const accessUrl = `https://i0.wp.com/eth.sucks/ipfs/${fileHash}`;
const accessUrl = `https://i0.wp.com/i0.img2ipfs.com/ipfs/${fileHash}`;
console.log(`图片访问链接: ${accessUrl}`);

// 返回成功的链接
Expand Down Expand Up @@ -663,4 +666,101 @@ async function handleRequest(request) {
return new Response('Internal Server Error', { status: 500 });
}
}


async function handleMtDpRequest(request) {
console.log('Request received for DP upload:', request.url);

if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}

try {
// 解析请求中的表单数据
const formData = await request.formData();
const file = formData.get('image'); // 前端上传的字段名为 'image'

if (!file) {
return new Response('No file uploaded', { status: 400 });
}

// 获取文件信息
const fileName = file.name;
const fileType = file.type; // 如 'image/jpeg'
const fileSize = file.size;

// 生成新的文件名(使用 MD5 和随机数)
const timeStamp = new Date().getTime().toString();
const randomNum = Math.floor(Math.random() * 100000).toString();
const hash = await crypto.subtle.digest('MD5', new TextEncoder().encode(timeStamp + randomNum));
const hashArray = Array.from(new Uint8Array(hash));
const md5Hash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
const newFileName = md5Hash + '.' + fileName.split('.').pop();

// 获取文件的最后修改时间(GMT 格式)
const lastModifiedDate = new Date().toUTCString();

// 创建新的 FormData,用于发送到大众点评的接口
const dpFormData = new FormData();
dpFormData.append('id', 'WU_FILE_0'); // 固定值
dpFormData.append('name', newFileName);
dpFormData.append('type', fileType);
dpFormData.append('lastModifiedDate', lastModifiedDate);
dpFormData.append('size', fileSize);
dpFormData.append('file', file, newFileName); // 文件字段名为 'file'

// 设置必要的头部信息
const dpHeaders = {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};

// 大众点评的上传接口 URL
const dpUrl = 'https://trust.dianping.com/upload.action';

// 发送请求到大众点评接口
const response = await fetch(dpUrl, {
method: 'POST',
headers: dpHeaders,
body: dpFormData
});

if (!response.ok) {
const errorText = await response.text();
console.error(`Upload failed: Status ${response.status}, Body: ${errorText}`);
return new Response(`Upload failed: ${errorText}`, { status: response.status });
}

// 解析大众点评接口的响应
const responseData = await response.json();
console.log('Response from DP API:', responseData);

if (responseData && responseData.isSuccess) {
let url = responseData.url;

// 转为 HTTPS 协议
url = url.replace('http://', 'https://');

// 随机替换域名前缀
const prefixes = ['img', 'p0', 'p1', 'p2'];
const randomPrefix = prefixes[Math.floor(Math.random() * prefixes.length)];
url = url.replace(/\/\/p0\./, `//${randomPrefix}.`);

// 成功,返回图片 URL
return new Response(url, {
status: 200,
headers: {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*' // 根据需要调整 CORS 策略
}
});
} else {
console.error('Upload failed:', responseData);
return new Response('Upload failed', { status: 500 });
}
} catch (error) {
console.error('Error in handleDpUploadRequest:', error);
return new Response('Internal Server Error', { status: 500 });
}
}

55 changes: 55 additions & 0 deletions python-uploader/test-mtdp2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import requests
import hashlib
import time
import os
import random

def upload_image(file_path):
api_url = "https://trust.dianping.com/upload.action"

# 获取文件名和 MIME 类型
file_name = os.path.basename(file_path)
file_type = "image/jpeg" # 根据文件实际类型修改,例如 'image/png'

# 生成 MD5 作为新文件名
new_file_name = hashlib.md5(str(time.time()).encode()).hexdigest() + os.path.splitext(file_name)[1]

# 获取文件的大小
file_size = os.path.getsize(file_path)

# 使用 GMT 格式的最后修改时间
last_modified_date = time.strftime('%a %b %d %Y %H:%M:%S GMT', time.gmtime(os.path.getmtime(file_path)))

# 上传请求的参数
post_data = {
"id": "WU_FILE_0",
"name": new_file_name,
"type": file_type,
"lastModifiedDate": last_modified_date,
"size": file_size,
}

# 打开文件并准备上传
with open(file_path, 'rb') as file:
files = {
"file": (new_file_name, file, file_type)
}
# 发起请求
response = requests.post(api_url, data=post_data, files=files)

# 检查响应结果
if response.status_code == 200:
response_data = response.json()
if response_data.get("isSuccess") == True:
url = response_data["url"]
# 随机替换前缀
prefix = random.choice(["img", "p0", "p1", "p2"])
url = url.replace("p0.", f"{prefix}.").replace("http://", "https://")
print("Upload successful:", url)
else:
print("Upload failed:", response_data.get("msg", "Unknown error"))
else:
print("HTTP error:", response.status_code, response.text)

# 调用上传函数,使用测试图片路径
upload_image(r"F:\Download\E9601BA8FB0DC48A8DF40509CD48069C (1).jpg")

0 comments on commit 73126c0

Please sign in to comment.