gpt4 book ai didi

ruby-on-rails - Rails 3 - 使用json上传图片

转载 作者:行者123 更新时间:2023-12-02 07:42:06 26 4
gpt4 key购买 nike

在我的 Rails 3 应用程序中,我有多个模型,每个模型都与另一个模型关联。

用户模型

has_many :departments
accepts_nested_attributes_for :departments

部门模型

has_many :projects
accepts_nested_attributes_for :projects

我正在尝试通过 postman REST client 插入数据使用 JSON。我已经找到了一些格式,除了 User 模型中有一个图像上传字段,我将使用 PaperClip gem 来处理该字段。

通过我的 Rails View ,它工作正常,但如何使用 postman 上传图像?

为了通过 REST 客户端上传,我需要与我的图像等效的 JSON 格式。

有什么方法可以将图像嵌入到 json 中,以便我可以使用 postman 休息客户端吗?

最佳答案

- 使用 Base64

What is Base64
When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings).

So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings. Why 64? Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.

-- 取自 What is base 64 encoding used for?

<小时/>

因此,一种方法是将 Base64 字符串放入您的 json 请求中,然后让您的应用对其进行解码。

 # Your request
{
'user':{
# ....
'picture':'GIF89a\xB4\x00\x1F\x00\xE7\xFD....'
}
}

这是您的模型可以执行的操作

 class User < ActiveRecord::Base
def convert_from_base64(image_data)
data = StringIO.new(Base64.decode64(image_data))
data.class.class_eval { attr_accessor :original_filename, :content_type }

tmp = Tempfile.new("base64")
tmp.write(data.read)
tmp.close

# only on *nix
data.content_type = IO.popen(["file", "--brief", "--mime-type",tmp.path],
in: :close, err: :close).read.chomp
data.original_filename = "picture." + data.content_type.split("/").last

data
end
end


# in your controller
def create
image_data = JSON.parse(params[:json])['user']['picture'] #or which ever field it is
params[:user][:picture] = @user.convert_from_base64(image_data)
# ....
end

但是快速浏览一下 POSTMAN 告诉我你必须自己进行编码。

<小时/>

或者
您可以只传递 url 而不是数据 - 如果 url 指向网络上可用的资源。

require "open-uri"

class User < ActiveRecord::Base
def picture_from_url(url)
self.picture = open(url)
end
end
# then just do
user.picture_from_url params[:user][:photo_url]

更新
Postman 实际上允许您构建一个附加图像的发布请求。这不是您要找的吗?

关于ruby-on-rails - Rails 3 - 使用json上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13911954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com