Download steemit images and update markdown automatically / 说说Steemit文章的备份:如何自动下载保存文章中的图片并自动更新markdown文本

yuxi(61)
Published in
#cn
Words
503
Reading
3 min
Listen
Play
9y

Sometimes we want to backup our steemit posts into our own blog/website. It is easy to backup the post text. However, it is a hard work to download all images from steemit to your web server and update image urls in the markdown manually. Here is a script to do the job automatically for you.

相信很多老博主和羽西一样,在Steemit发布了文章后都想把文章在自己博客上做个备份。文章本身是Markdown,很容易备份,只需要复制粘贴就可以了。但文章中的配图都保存在Steem的区块链上,如果想要把图片一个一个的复制到本地,再手工更新备份下来的Markdown文本,工作量就太大了,因此,动手写了这个小程序来做这件工作。

For example, the steemit markdown source looks like:

比如,在Steemit中的源文件是这样的:

Paragraph 1

![](https://steemitimages.com/DQmcb73AkP8hWARdtG7iTGKTst6RccxYS3YS82nmvMxneoq/image.png)

Paragraph 2

![](https://steemitimages.com/DQmRTtZFKEzGUCWyCEJ7jeyML9akAAGYW7c6pVB87NogZW1/image.png)

Paragraph 3

![](https://steemitimages.com/DQmapPpzLqGs2xAwnKSxzwzZUUqos8QAqATLiqCHdo4rfpq/image.png)

After processing, the markdown looks like:

经过程序处理后的文件是这样的(所有的图片都自动保存到了本地,并自动更新了Markdown中的图片地址):

Paragraph 1

![](/images/CFUUKPGDIGFPOTPV.png)

Paragraph 2

![](/images/PRMXOOVRLVXQRWNY.png)

Paragraph 3

![](/images/NIUUOYNTWZDFIWXO.png)

The script is written in Ruby. As it is just a handy tool for myself, no exception handling in the code

程序是用Ruby写的,由于只是自用,就没有做任何的容错处理。这里和大家分享一下。

require 'open-uri'

if ARGV.length != 4
  puts 'Usage: ruby backup.rb SOURCE_FILE TARGET_FILE WWW_ROOT RELATIVE_PATH'
  puts 'e.g. ruby backup.rb /tmp/gump.md /tmp/gump2.md /var/www/ images/'
  exit
end

url_mappings = Hash.new

source_file   = ARGV[0]
target_file   = ARGV[1]
www_root      = ARGV[2]
relative_path = ARGV[3]

s = IO.read(source_file)

s.scan(/(!\[.*?\]\()(.+?)(\))/).each do |a,image_url,c|
  filename = (0...16).map { (65 + rand(26)).chr }.join + '.png'
  open(www_root + relative_path + filename, 'wb') do |file|
    file << open(image_url).read
  end
  url_mappings[a+image_url+c] = a + '/' + relative_path + filename + c
end

url_mappings.each do |old, new|
  s = s.gsub(old, new)
end

File.open(target_file, 'w') {|f| f.write(s) }

To run the script, type:

如果想要运行这个程序,只需要键入:

ruby backup.rb /tmp/gump.md /tmp/gump2.md /var/www/ images/

The first parameter is the original markdown file name
The second parameter is the new markdown file name
The third parameter is the root path of your web server
The fourth parameter is the relative path for the downloaded images

其中,
第一个参数是你把markdown文本保存到本地的文件名
第二个参数是程序进行图片下载并更新markdown图片链接后保存的文件名
第三个参数是你的网站本地的根目录
第四个参数是图片文件在网站中的相对目录

https://steemit.com 首发。非常感谢阅读,欢迎FOLLOW, Resteem和Upvote yuxi@yuxi 激励我创作更多更好的内容。

Download steemit images and update markdown automatically / 说说Steem... | Ecency