# 批量操作帮助：将热链接图片替换为本地图片文件

**URL:** https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912
**Category:** Development
**Created:** [2023年五月13日 21:07 UTC](https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912 "2023-05-13T21:07:13Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![shyguy](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/shyguy/32/295079_2.png) [@shyguy](https://meta.discourse.org/u/shyguy)
#### Post date: [2023年五月13日 21:07 UTC](https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912/1 "2023-05-13T21:07:13Z")

</div>

场景：

- 一个免费的图片托管服务（在此示例中为 `foo-host`）已失效，并且一个 discourse 论坛的帖子中包含大量热链接的图片
- 在图片失效之前，它们已被手动备份并存在于本地文件系统中
- 存在一个图片 URL 和本地文件路径之间的映射：`get_paths_from_hotlinked_urls()`

我该如何：

1. 为这些图片中的每一个在 rails 中创建一个附件，并且
2. 正确地将它们添加到帖子中？

```ruby
image_host_domain = 'foo-host.com'

hotlink_posts = Post.where('cooked ~ ?', image_host_domain)
puts "找到了 #{hotlink_posts.length} 个包含热链接图片的帖子..."

hotlink_posts.each do |p|
  # 获取帖子中包含 image_host_domain 的所有 URL
  urls = URI.extract(p.cooked).select { |url| url[/#{Regexp.quote(image_host_domain)}/] }

  local_paths = get_paths_from_hotlinked_urls(urls)

  new_raw = p.raw
  urls.each.with_index do |url, i|
    next if local_paths[i].blank?

    # ***** TODO: 1) 将 local_paths[i] 作为附件“上传”
    # 并正确地将其与帖子关联

    # ***** TODO: 2) 用附件替换热链接
    # new_raw = new_raw...
  end

  p.update(raw: new_raw)
end

```

抱歉发帖质量不高。今天有点压力，哈哈

有人能指点一下方向吗？如果太麻烦，不要求提供完整解决方案。谢谢

---

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [2023年五月14日 02:08 UTC](https://meta.discourse.org/t/bulk-action-help-replace-hotlinked-images-with-local-image-files/264912/2 "2023-05-14T02:08:44Z")

</div>

您可以查看导入脚本，了解如何上传文件以及插入这些上传的 HTML 的示例。
