载波+ json 响应中的 Mongoid 完整 url

发布于 2024-12-27 04:55:57 字数 300 浏览 3 评论 0原文

我正在尝试为移动应用程序构建 api,并使用 Carrierwave 和 Mongoid。上传和检索图像一切正常,但是当我生成 json 响应时,图像 url 仅显示 path/to/image.png 而不是 http://localhost:3000/path/to/image.png

如何让我的应用程序生成图像的完整 url。我在谷歌上进行了广泛的搜索,但无法找到任何可靠的解决方案。

预先感谢您的帮助。

I am trying to build an api for a mobile app and am using Carrierwave and Mongoid. Everything works fine with uploading and retrieving the images, but when i generate the json response the image urls simply show a path/to/image.png instead of http://localhost:3000/path/to/image.png.

How do I get my app to generate the full url to the image. I have done an extensive search on google but am unable to find any solid solutions.

Thanks in advance for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

捂风挽笑 2025-01-03 04:55:58

我认为默认情况下你不能使用 Carrierwave 来做到这一点,但是你可以通过这个猴子补丁来解决这个问题,

module CarrierWave::Uploader::Url
  def url
    if $request
      if file.respond_to?(:url) and not file.url.blank?
        $request.protocol + $request.host_with_port + file.url
      elsif current_path
        $request.protocol + $request.host_with_port + (base_path || "") + File.expand_path(current_path).gsub(File.expand_path(root), '')
      end
    else
      raise ArgumentError, "Request object is empty"
    end

  end

end

因为你无法从上传者(任何模型)访问 Rails session/request 信息,你需要定义application_controller 中的 before_filter 来加载请求数据

  before_filter :load_request

  def load_request
    $request = request
  end

我仅在本地存储/mongoid 中测试了此补丁。我不知道这在亚马逊 s3/fog 中如何工作..

希望这有帮助

I dont think you can do this with carrierwave by default, but you can workaround this by this monkey patch

module CarrierWave::Uploader::Url
  def url
    if $request
      if file.respond_to?(:url) and not file.url.blank?
        $request.protocol + $request.host_with_port + file.url
      elsif current_path
        $request.protocol + $request.host_with_port + (base_path || "") + File.expand_path(current_path).gsub(File.expand_path(root), '')
      end
    else
      raise ArgumentError, "Request object is empty"
    end

  end

end

since you cannot access the rails session/request info from the uploader(any model), you need to define the before_filter in application_controller to load the request data

  before_filter :load_request

  def load_request
    $request = request
  end

I have tested this patch only in local storage/mongoid. I dont know how this will work in amazon s3/fog..

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文