2023-08-13 12:05PM
1. 创建文件 scripts/fetch_images_and_rename_image_urls_in_database.rb
运行脚本
ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'production'
require File.expand_path(File.dirname(__FILE__) + '/../config/environment')
require 'rails'
require 'rubygems'
require 'json'
# 仅处理一个article
def fetch_image_and_rename_image_urls article
puts "== processing: id: #{article.id}, title: #{article.title}"
regexp = /https:\/\/img-blog\.csdnimg\.cn\/\w+.png/
# 1. 获得某个article content中的所有图片
article.content.scan(regexp).each do |url|
puts url
file_name = url.split('/').last
# 2. 把这些图片都抓取到本地,并重新命名
# https://img-blog.csdnimg.cn/13e29d1a43axxxxxxxxxxxxxxxxx.png
#你想要把图片存放在哪个文件夹下面就把public/images/替换为它
command = "wget #{url} -O public/images/#{file_name}"
`#{command}`
# 3. 把content中的老图片的URL, 替换成新图片的URL
# https://img-blog.csdnimg.cn/13e29d1a43axxxxxxxxxxxxxxxxx.png
# https://img-blog.csdnimg.cn/13e29d1a43axxxxxxxxxxxxxxxxx.png => /images/13e29d1a43axxxxxxxxxxxxxxxxx.png
# 也就是说. https://img-blog.csdnimg.cn/ => /images
end
# 注意,记得把/images替换为你想要存放图片的文件
article.content = article.content.gsub("https://img-blog.csdnimg.cn", "/images")
article.save!
end
# 处理所有
Article.all.each do |article|
fetch_image_and_rename_image_urls article
end
2. 然后运行它 bundle exec ruby scripts/fetch_images_and_rename_image_urls_in_database.rb
运行完这个脚本,再回到本地的浏览器查看就发现图片已经拉去成功了
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论