栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

✅作者简介:大家好我是五维星空,目前是某国企的一名Java全栈程序员,热爱技术、喜欢代码,希望我的文章能给大家带来收获。

✅个人主页:五维星空的csdn博客

✅系列专栏:小工具

✅如果觉得博主的文章还不错的话,请三连支持一下博主哦✅

最近“懒a”发作,懒得将markdown文件中的图片一个个上传然后替换地址,思来想去,搞个小工具呗~

功能

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

✅我是五维星空,一名Java全栈开发者,热爱技术,感谢各位大大的点赞、收藏和评论,我们下期再见!

五维星空 - 分享前后端技术!(公 众 号:五维星空 )

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1002471.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号