import os
import requests
import csv
def upload_images(folder_path, api_url, output_csv):
# 创建CSV文件并写入标题行
with open(output_csv, mode='w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Image Name', 'URL'])
# 遍历指定文件夹下的所有文件
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# 检查是否为文件并且是图片
if os.path.isfile(file_path) and filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
with open(file_path, 'rb') as f:
files = {'file': (filename, f)}
# 发送POST请求
response = requests.post(api_url, files=files)
# 检查响应状态码
if response.status_code == 200:
try:
# 假设URL在响应的JSON体中,键为'url'
filePath = response.json()['filePath']
# 写入CSV文件
writer.writerow([filename, filePath])
print(f"成功上传 {filename},URL: {filePath}")
except KeyError:
print(f"响应中没有找到URL字段:{response.filePath}")
else:
print(f"上传 {filename} 失败,状态码: {response.status_code}")
# 调用函数
folder_path = '/path/to/your/images'
api_url = 'http://127.0.0.1:80/api/upload'
output_csv = 'image_urls.csv'
upload_images(folder_path, api_url, output_csv)