Ruby on rails Rails API carrierwave无法上载从API客户端发送的文件
Im使用unirest在节点JS中创建一个客户端API,该API将向rails API发送数据。我必须将文件更改为base64编码字符串,如下所示:Ruby on rails Rails API carrierwave无法上载从API客户端发送的文件,ruby-on-rails,node.js,api,Ruby On Rails,Node.js,Api,Im使用unirest在节点JS中创建一个客户端API,该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"
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>
您可以使用以下gem将base64编码字符串与carrierwave一起使用: 您只需在
ProductImage
类中将mount\u uploader
更改为mount\u base64\u uploader
,然后您就可以将base64编码字符串分配给图像字段:
product_image = ProductImage.new(params)
解决了
我更改了:
"image": fs.readFileSync(path).toString('base64')
致:
这样就不需要对文件进行解码。谢谢大家在您尝试保存数据库时显示日志。@MateuszCzerwiński请查看我的更新问题try without
Base64。decode64
,也许您可以将数据存储为Base64(?)。
"image": fs.readFileSync(path).toString('base64')
"image": fs.createReadStream(path)