功能
读取目录下的markdown文件,将其中的本地图片路径转为阿里云OSS外链,点一下,玩一年,装备不花一分钱,爽歪歪哈哈哈~
程序源码
# -*- coding: utf-8 -*-
import json
import chardet
import oss2
import os
import re
class UploadFile:
"""
上传markdown中的图片至阿里云
"""
def __init__(self, accessKeyId, secret, endpoint, bucketName, basePath, destPath):
"""
初始化
"""
self.accessKeyId = accessKeyId
self.secret = secret
self.endpoint = endpoint
self.bucketName = bucketName
self.basePath = basePath
self.destPath = destPath
# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
# accessKeyId Secret
self.auth = oss2.Auth(accessKeyId, secret)
# 填写Bucket名称。
# endpoint bucketName
self.bucket = oss2.Bucket(self.auth, endpoint, bucketName)
def find_all_file(self, base):
"""
遍历文件夹
"""
for root, ds, fs in os.walk(base):
for f in fs:
if f.endswith('.md'):
fullname = os.path.join(root, f)
yield fullname
def upload_file(self, sourcePath, destPath):
"""
上传文件
"""
fileName = sourcePath.split('\\')[-1]
destFile = destPath + fileName
self.bucket.put_object_from_file(destFile, sourcePath)
return destFile
def get_encoding(self, filePath):
"""获取文件编码格式"""
with open(filePath, 'rb') as f:
tmp = chardet.detect(f.read())
return tmp['encoding']
def update_img_path(self, filePath):
"""解析markdown文件中的图片并上传替换"""
encode = self.get_encoding(filePath)
regx = r'!\[.*\]\((.*)\)'
resLines = []
with open(filePath, 'r+', encoding=encode) as file:
lines = file.readlines()
for line in lines:
regGroup = re.match(regx, line)
if regGroup:
# print('md的图片:'+oldStr)
localPath = regGroup.group(1)
if localPath.startswith('http'):
resLines.append(line)
continue
# print('地址:'+localPath)
destFile = self.upload_file(localPath, self.destPath)
url = self.endpoint.replace('https://', 'https://' + self.bucketName + '.') \
+ '/' + destFile
resLines.append(line.replace(localPath, url))
# print('最终的:'+url)
else:
resLines.append(line)
self.write_file(filePath, resLines)
def update_img_dir_path(self):
"""上传文件夹下的所有markdown文件中的图片并替换"""
if os.path.isdir(self.basePath):
for filePath in self.find_all_file(self.basePath):
self.update_img_path(filePath)
else:
self.update_img_path(self.basePath)
def write_file(self, filePath, content):
"""覆盖写入文件"""
encode = self.get_encoding(filePath)
with open(filePath, 'w+', encoding=encode) as file:
file.writelines(content)
if __name__ == "__main__":
accessKeyId = '你的id'
secret = '你的密钥'
#https://oss-cn-hangzhou.aliyuncs.com
endpoint = '你的endpoint地址'
bucketName = '你的bucket名称'
basePath = "本地文件夹路径"
#'img/markdown/后端/Oracle/'
destPath = '远端文件夹路径,记得不用以/开头'
# 初始化配置
upload = UploadFile(accessKeyId,secret,endpoint,bucketName,basePath,destPath)
# 开始解析markdown中的图片并上传
upload.update_img_dir_path()
print('如果本文对你有用,微信搜索“五维星空”,点个关注吧~')