def operat_md_media(self, md_content, create_user): # 查找MD内容中的静态文件 pattern = r"\!\[.*?\]\(.*?\)" media_list = re.findall(pattern, md_content) # print(media_list) # 存在静态文件,进行遍历 if len(media_list) > 0: for media in media_list: media_filename = media.split("(")[-1].split(")")[0] # 媒体文件的文件名 # 存在本地图片路径 if media_filename.startswith( "./") or media_filename.startswith("/"): # 获取文件后缀 file_suffix = media_filename.split('.')[-1] if file_suffix.lower() not in settings.ALLOWED_IMG: continue # 判断本地图片路径是否存在 if media_filename.startswith("./"): temp_media_file_path = os.path.join( self.temp_dir, media_filename[2:]) else: temp_media_file_path = os.path.join( self.temp_dir, media_filename[1:]) if os.path.exists(temp_media_file_path): # 如果存在,上传本地图片 dir_name = upload_generation_dir() # 获取当月文件夹名称 # 复制文件到媒体文件夹 copy2_filename = dir_name + '/' + str( time.time()) + '.' + file_suffix new_media_file_path = shutil.copy2( temp_media_file_path, settings.MEDIA_ROOT + copy2_filename) # 替换MD内容的静态文件链接 new_media_filename = new_media_file_path.split( settings.MEDIA_ROOT, 1)[-1] new_media_filename = '/media' + new_media_filename # 图片数据写入数据库 Image.objects.create( user=create_user, file_path=new_media_filename, file_name=str(time.time()) + '.' + file_suffix, remark='本地上传', ) md_content = md_content.replace( media_filename, new_media_filename) else: pass return md_content # 不存在静态文件,直接返回MD内容 else: return md_content
def convert_img(self,image): with image.open() as image_bytes: file_suffix = image.content_type.split("/")[1] file_time_name = str(time.time()) dir_name = upload_generation_dir() # 获取当月文件夹名称 # 图片在媒体文件夹内的路径,形如 /202012/12542542.jpg copy2_filename = dir_name + '/' + file_time_name + '.' + file_suffix # 文件的绝对路径 形如/home/MrDoc/media/202012/12542542.jpg new_media_file_path = settings.MEDIA_ROOT + copy2_filename # 图片文件的相对url路径 new_media_filename = '/media' + copy2_filename # 图片数据写入数据库 Image.objects.create( user=self.create_user, file_path=new_media_filename, file_name=file_time_name + '.' + file_suffix, remark='本地上传', ) with open(new_media_file_path, 'wb') as f: f.write(image_bytes.read()) return {"src": new_media_filename}