【问题标题】:Post image from Rails从 Rails 发布图片
【发布时间】:2017-06-22 20:28:36
【问题描述】:

我的应用程序中有一个 Base64 编码的图像。我想在其他地方重新发布该图像,但它在目的地将内容类型设置为 multipart/form-data。我如何上传这张图片?

file_name = permitted_params[:file_name]
file_contents = permitted_params[:file_contents]

file = Tempfile.new( file_name )
file.binmode
file.write( Base64.decode64( file_contents ) )
file.rewind()

raw_response = RestClient.put(
    url,
    { 'upload' => file, :content_type => 'image/jpeg' },
    :headers => {:content_type => 'image/jpeg'}
)

更新(已解决)

我需要使用 RestClient,因为我需要将它传递到另一台服务器(因此 PUT 中的“url”)。

我的问题是在解码图像时我没有去掉

data:image/jpeg;base64,

然后使用此代码:

raw_response = RestClient.put(url,
                              file_binary,
                              {:content_type => imageContentType})

我能够让它放置图像并设置正确的内容类型。不过,下面的答案确实有所帮助,因为我尝试了它以确保图像被正确解码,但事实并非如此。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    这很简单。首先,您需要解码 base64 编码文件。您将获得二进制文件表示。接下来使用ActionController 中的send_data 发送二进制数据。我还设置了一个文件名,以便将其传递给用户。

    require 'base64'
    
    class SomeController < ApplicationController
      def some_action
        file_name            = permitted_params[:file_name]
        file_base64_contents = permitted_params[:file_contents]
        file_binary_contents = Base64.decode64(file_base64_contents)
    
        # https://apidock.com/rails/ActionController/Streaming/send_data
        send_data file_binary_contents, filename: file_name
      end
    end
    

    我建议您使用错误处理来更新此实现,以提高应用的安全性。还有一件事,不要使用RestClient。为什么在这里需要它? Rails 为您提供了从控制器进行 HTTP 通信所需的一切。

    如果您对此有任何疑问,请提出。祝你好运。

    【讨论】:

      猜你喜欢
      • 2017-07-10
      • 2020-07-25
      • 2011-08-18
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多