Python根據文件URL將文件轉為Base64字符串
1.效果
1.1本地文件

1.2網絡文件

2.fileToBase64.py
輸出日志:/logs/file-to-base64--{當前時間}.log
開放端口:5000
2.1腳本內容
from flask import Flask, request, jsonify
import requests
import base64
import logging
import os
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime
import mimetypes
app = Flask(__name__)
# 配置日志目錄
LOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
# 按年月日構建日志文件路徑
current_date = datetime.now().strftime('%Y%m%d')
LOG_FILE = os.path.join(LOG_DIR, f'file-to-base64-{current_date}.log')
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
TimedRotatingFileHandler(
LOG_FILE,
when='midnight',
interval=1,
backupCount=30,
encoding='utf-8'
)
]
)
# 輸入:{fileUrl:xxx} 輸出:{fileExt:文件類型,len:字符串長度,str:base64字符串}
@app.route('/file-to-base64', methods=['POST'])
def file_to_base64():
"""根據文件URL(本地路徑或網絡路徑)將文件轉換為Base64字符串"""
# 每次請求時打印日志,分割
logging.info("-----------------------------------------------------------------------------------------------------------------")
# 1.獲取請求頭中的 Authorization 字段(可選)
authorization = request.headers.get('Authorization')
if authorization != 'dPvnRNtrQhHMxDfGoOEa':
logging.warning(f"Authorization 字段驗證失敗: {authorization}")
return jsonify({"error": "Authorization verification failed"}), 401
# 2.獲取請求參數
data = request.json
if not data or 'file_url' not in data:
logging.warning("請求參數缺失")
return jsonify({"error": "file_url is required"}), 400
# 3. 開始處理文件轉換
file_url = data['file_url']
logging.info(f"開始處理文件轉換,URL: {file_url}")
try:
# 3.1 讀取本地文件或網絡文件
if file_url.startswith('file://') or os.path.exists(file_url):
# 3.1.1 處理本地文件
if file_url.startswith('file://'):
file_path = file_url[7:]
else:
file_path = file_url
with open(file_path, 'rb') as f:
file_bytes = f.read()
content_type = mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
else:
# 3.1.2 處理網絡文件
# 問題:HTTPSConnectionPool(host='xx.xx.xx.xx', port=443): Max retries exceeded with url
# 解決方法:添加 verify=False 忽略證書驗證
response = requests.get(file_url, verify=False)
response.raise_for_status()
file_bytes = response.content
content_type = response.headers.get('Content-Type', '')
# 3.2 通過Content-Type判斷文件類型
file_extension = get_file_extension_from_content_type(content_type)
# 3.3 將文件轉換為Base64字符串
base64_encoded = base64.b64encode(file_bytes).decode('utf-8')
# 3.4 添加MIME類型前綴返回(可選)
if content_type:
base64_encoded = f"data:{content_type};base64,{base64_encoded}"
# 3.5 記錄轉換結果
logging.info(f"轉換成功!文件類型:{file_extension},Base64字符串長度: {len(base64_encoded)}")
return jsonify({
"fileExt":file_extension,
"len":len(base64_encoded),
"str": base64_encoded
})
# 4. 異常處理
except requests.RequestException as e:
logging.error(f"請求URL: {file_url}時出錯: {e}")
return jsonify({"error": str(e)}), 500
except Exception as e:
logging.error(f"請求URL: {file_url}轉換發(fā)生未知錯誤: {e}")
return jsonify({"error": "Internal server error"}), 500
def get_file_extension_from_content_type(content_type):
"""根據Content-Type獲取文件擴展名"""
# 去除字符集信息,只保留MIME類型部分
mime_type = content_type.split(';')[0].strip().lower()
mime_to_extension = {
# 圖片類型
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif',
'image/bmp': 'bmp',
'image/webp': 'webp',
'image/svg+xml': 'svg',
# 音頻類型
'audio/wav': 'wav',
'audio/mpeg': 'mp3',
'audio/ogg': 'ogg',
'audio/webm': 'weba',
# 視頻類型
'video/mp4': 'mp4',
'video/webm': 'webm',
'video/ogg': 'ogv',
# 文檔類型
'application/pdf': 'pdf',
'application/msword': 'doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
'application/vnd.ms-excel': 'xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
'application/vnd.ms-powerpoint': 'ppt',
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
# 文本類型
'text/plain': 'txt',
'text/html': 'html',
'text/css': 'css',
'text/javascript': 'js',
'application/javascript': 'js',
'application/json': 'json',
'application/xml': 'xml',
# 壓縮文件
'application/zip': 'zip',
'application/x-rar-compressed': 'rar',
'application/x-tar': 'tar',
'application/x-gzip': 'gz',
# 其他常見類型
'application/octet-stream': 'bin',
'application/x-shockwave-flash': 'swf',
'application/x-font-ttf': 'ttf',
'application/x-font-woff': 'woff',
'application/x-font-woff2': 'woff2'
}
return mime_to_extension.get(mime_type, 'unknown')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)2.2啟動查詢服務
cd /usr/ai/codes/fileutil # 運行 python3 fileToBase64.py # 后臺運行 nohup python3 fileToBase64.py > /dev/null 2>&1 & # 查看進程 ps -ef | grep fileToBase64.py
2.3訪問
注意Header中Authorization=dPvnRNtrQhHMxDfGoOEa目前是寫死的。
curl --location --request POST 'http://127.0.0.1:5000/file-to-base64' \
--header 'Authorization: dPvnRNtrQhHMxDfGoOEa' \
--header 'Content-Type: application/json' \
--data-raw '{"file_url":"https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/samantha/logo-icon-white-bg.png"}'file_url:必填,需要轉換的文件地址(公網http地址,或服務器所在文件的絕對路徑)
舉例:
{"file_url":"https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/samantha/logo-icon-white-bg.png"}
{"file_url":"/usr/ai/codes/fileutil/readMe1.0.0.txt"}
json輸出:
{
"fileExt": "txt",
"len": 131,
"str": "data:text/plain;base64,5LiL6L295Zyw5Z2A77yaDQpodHRwczovL2NvZGVsb2FkLmdpdGh1Yi5jb20vbGFuZ2dlbml1cy9kaWZ5L3ppcC9yZWZzL2hlYWRzL21haW4="
}異常json輸出示例:
{
"error": "file_url is required"
}
{
"errmsg": "Invalid URL 'none': No scheme supplied. Perhaps you meant https://none?"
}到此這篇關于Python根據文件URL將文件轉為Base64字符串的文章就介紹到這了,更多相關Python文件轉Base64內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python 利用pywifi模塊實現連接網絡破解wifi密碼實時監(jiān)控網絡
這篇文章主要介紹了python 利用pywifi模塊實現連接網絡破解wifi密碼實時監(jiān)控網絡,需要的朋友可以參考下2019-09-09
Python使用enum模塊獲取枚舉成員索引號的四種方法詳解
在 Python 中,可以使用 enum 模塊創(chuàng)建枚舉類型,并通過遍歷枚舉成員來獲取其索引號,本文介紹了常用的四種方法,大家可以根據自己的需要進行選擇2026-04-04
typing.Dict和Dict的區(qū)別及它們在Python中的用途小結
當在 Python 函數中聲明一個 dictionary 作為參數時,我們一般會把 key 和 value 的數據類型聲明為全局變量,而不是局部變量。,這篇文章主要介紹了typing.Dict和Dict的區(qū)別及它們在Python中的用途小結,需要的朋友可以參考下2023-06-06

