Markdown文件中的图片批量上传至阿里云并更新本地文件中的图片路径【Python】

功能

读取目录下的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('如果本文对你有用,微信搜索“五维星空”,点个关注吧~')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值