Python根據(jù)文件URL將文件轉(zhuǎn)為Base64字符串
1.效果
1.1本地文件

1.2網(wǎng)絡(luò)文件

2.fileToBase64.py
輸出日志:/logs/file-to-base64--{當(dāng)前時(shí)間}.log
開放端口:5000
2.1腳本內(nèi)容
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)
# 按年月日構(gòu)建日志文件路徑
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:字符串長(zhǎng)度,str:base64字符串}
@app.route('/file-to-base64', methods=['POST'])
def file_to_base64():
"""根據(jù)文件URL(本地路徑或網(wǎng)絡(luò)路徑)將文件轉(zhuǎn)換為Base64字符串"""
# 每次請(qǐng)求時(shí)打印日志,分割
logging.info("-----------------------------------------------------------------------------------------------------------------")
# 1.獲取請(qǐng)求頭中的 Authorization 字段(可選)
authorization = request.headers.get('Authorization')
if authorization != 'dPvnRNtrQhHMxDfGoOEa':
logging.warning(f"Authorization 字段驗(yàn)證失敗: {authorization}")
return jsonify({"error": "Authorization verification failed"}), 401
# 2.獲取請(qǐng)求參數(shù)
data = request.json
if not data or 'file_url' not in data:
logging.warning("請(qǐng)求參數(shù)缺失")
return jsonify({"error": "file_url is required"}), 400
# 3. 開始處理文件轉(zhuǎn)換
file_url = data['file_url']
logging.info(f"開始處理文件轉(zhuǎn)換,URL: {file_url}")
try:
# 3.1 讀取本地文件或網(wǎng)絡(luò)文件
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 處理網(wǎng)絡(luò)文件
# 問題:HTTPSConnectionPool(host='xx.xx.xx.xx', port=443): Max retries exceeded with url
# 解決方法:添加 verify=False 忽略證書驗(yàn)證
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 將文件轉(zhuǎn)換為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 記錄轉(zhuǎn)換結(jié)果
logging.info(f"轉(zhuǎn)換成功!文件類型:{file_extension},Base64字符串長(zhǎng)度: {len(base64_encoded)}")
return jsonify({
"fileExt":file_extension,
"len":len(base64_encoded),
"str": base64_encoded
})
# 4. 異常處理
except requests.RequestException as e:
logging.error(f"請(qǐng)求URL: {file_url}時(shí)出錯(cuò): {e}")
return jsonify({"error": str(e)}), 500
except Exception as e:
logging.error(f"請(qǐng)求URL: {file_url}轉(zhuǎn)換發(fā)生未知錯(cuò)誤: {e}")
return jsonify({"error": "Internal server error"}), 500
def get_file_extension_from_content_type(content_type):
"""根據(jù)Content-Type獲取文件擴(kuò)展名"""
# 去除字符集信息,只保留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啟動(dòng)查詢服務(wù)
cd /usr/ai/codes/fileutil # 運(yùn)行 python3 fileToBase64.py # 后臺(tái)運(yùn)行 nohup python3 fileToBase64.py > /dev/null 2>&1 & # 查看進(jìn)程 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:必填,需要轉(zhuǎn)換的文件地址(公網(wǎng)http地址,或服務(wù)器所在文件的絕對(duì)路徑)
舉例:
{"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?"
}到此這篇關(guān)于Python根據(jù)文件URL將文件轉(zhuǎn)為Base64字符串的文章就介紹到這了,更多相關(guān)Python文件轉(zhuǎn)Base64內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 利用pywifi模塊實(shí)現(xiàn)連接網(wǎng)絡(luò)破解wifi密碼實(shí)時(shí)監(jiān)控網(wǎng)絡(luò)
這篇文章主要介紹了python 利用pywifi模塊實(shí)現(xiàn)連接網(wǎng)絡(luò)破解wifi密碼實(shí)時(shí)監(jiān)控網(wǎng)絡(luò),需要的朋友可以參考下2019-09-09
python字符串轉(zhuǎn)換成浮點(diǎn)數(shù)的實(shí)現(xiàn)方式
這篇文章主要介紹了python字符串轉(zhuǎn)換成浮點(diǎn)數(shù)的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2026-03-03
python 從遠(yuǎn)程服務(wù)器下載東西的代碼
python實(shí)現(xiàn)從遠(yuǎn)程服務(wù)器下載東西的代碼,有需要的朋友可以參考下2013-02-02
Python使用enum模塊獲取枚舉成員索引號(hào)的四種方法詳解
在 Python 中,可以使用 enum 模塊創(chuàng)建枚舉類型,并通過遍歷枚舉成員來獲取其索引號(hào),本文介紹了常用的四種方法,大家可以根據(jù)自己的需要進(jìn)行選擇2026-04-04
Pandas 透視表和交叉表的實(shí)現(xiàn)示例
本文主要介紹了Pandas 透視表和交叉表的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
typing.Dict和Dict的區(qū)別及它們?cè)赑ython中的用途小結(jié)
當(dāng)在 Python 函數(shù)中聲明一個(gè) dictionary 作為參數(shù)時(shí),我們一般會(huì)把 key 和 value 的數(shù)據(jù)類型聲明為全局變量,而不是局部變量。,這篇文章主要介紹了typing.Dict和Dict的區(qū)別及它們?cè)赑ython中的用途小結(jié),需要的朋友可以參考下2023-06-06
python腳本實(shí)現(xiàn)mp4中的音頻提取并保存在原目錄
這篇文章主要介紹了python腳本實(shí)現(xiàn)mp4中的音頻提取并保存在原目錄,本文給大家通過實(shí)例代碼介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02

