我使用 unirest 在 Node JS 中创建一个客户端 API,它将向 Rails API 发送数据。我必须将文件更改为 Base64 编码的字符串,如下所示:
unirest.post('http://localhost:3000/api/v1/image_uploaders')
.headers({'Content-Type': 'multipart/form-data'})
.field({
"product_id": 12,
"variant_id": 1,
"image": fs.readFileSync(path).toString('base64')
}) // Form field
.end(function (response) {
console.log(response.body);
});
在 Rails 端,这是处理请求的:
def create
variant = Variant.where(id: params[:variant_id]).first
if variant
product_image = ProductImage.new
product_image.image = StringIO.new(Base64.decode64(params[:image]))
product_image.product_id = params[:product_id]
product_image.variant_id = params[:variant_id]
if product_image.save
render json: true, status: :ok
else
render json: false, status: :bad_request
end
else
render json: false, status: :bad_request
end
end
我没有上传文件。任何想法?谢谢。
更新
我收到此错误消息:
undefined method `unpack'
for #<ActionDispatch::Http::UploadedFile:0x007fe47ac26f80>
指向这一行:
product_image.image = StringIO.new(Base64.decode64(params[:image]))
最佳答案
您可以使用以下 gem 将 Base64 编码的字符串与载波一起使用:
https://github.com/lebedev-yury/carrierwave-base64
您只需将 ProductImage
类中的 mount_uploader
更改为 mount_base64_uploader
,然后即可将 base64 编码的字符串分配给您的图像字段:
product_image = ProductImage.new(params)
关于ruby-on-rails - Rails API Carrierwave 无法上传从 API 客户端发送的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33645252/