最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python根據(jù)文件URL將文件轉(zhuǎn)為Base64字符串

 更新時(shí)間:2025年08月13日 10:08:15   作者:yqwang_cn  
這篇文章主要為大家詳細(xì)介紹了Python根據(jù)文件URL(本地路徑或網(wǎng)絡(luò)路徑)將文件轉(zhuǎn)為Base64字符串,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

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)文章

最新評(píng)論

文昌市| 霍林郭勒市| 察雅县| 皋兰县| 革吉县| 长子县| 安岳县| 吉林市| 康马县| 凌源市| 合阳县| 德惠市| 那曲县| 武城县| 固始县| 潢川县| 江川县| 天长市| 竹溪县| 如皋市| 宝清县| 石城县| 洞口县| 定边县| 延川县| 定日县| 胶南市| 肥乡县| 泊头市| 秦皇岛市| 喜德县| 竹溪县| 涟水县| 和硕县| 会宁县| 嘉义市| 双峰县| 交城县| 垫江县| 文安县| 平南县|