如何在Post体中包含图像数据和边界?

问题描述 投票:0回答:1

我需要使用Ruby在Post请求的主体中包含一个图像。该示例使用Bing Visual Search API查找与Post正文中发送的图像类似的图像。我得到了一个结果,但它是空的JSON。设置Post主体的代码显然有问题。我是Ruby语言的新手。

Post主体中有文本边界必须包含在图像数据中。我知道查询有效,因为我可以使用C#或Java发送相同的请求并获得结果。我试过base64encode图像数据,只是将文件读入Post数组。

# include libs
require 'net/https'
require 'uri'
require 'json'
require 'base64'

accessKey = "Access_Key_String"
uri  = "https://api.cognitive.microsoft.com"
path = "/bing/v7.0/images/visualsearch"
batchNumber = "097ad727-862d-4720-93c4-08f7038cea7c"
fileName = "ElectricBike.jpg"

if accessKey.length != 32 then
    puts "Invalid Bing Search API subscription key!"
    puts "Please paste yours into the source code."
    abort
end

def BuildFormDataStart(batNum, fileName)
    startBoundary = "--batch_" + batNum
    return startBoundary + "\r\n" + "Content-Disposition: form-data; 
    name=\"image\"; filename=" + "\"" + fileName + "\"" + "\r\n\r\n"    
end

def BuildFormDataEnd(batNum)
    return "\r\n\r\n" + "--batch_" + batNum + "--" + "\r\n"
end

# Construct the endpoint uri.
uri = URI(uri + path)

# Load the parts of the post body into an array.
post_body = []

# Add the file Data
post_body << BuildFormDataStart(batchNumber, fileName)

post_body << File.read(fileName) #Base64.encode64(File.read(fileName))

post_body << BuildFormDataEnd(batchNumber)

# Create the HTTP objects
header = {'Ocp-Apim-Subscription-Key': accessKey}

# Create the request.
request = Net::HTTP::Post.new(uri, 'knowledgeRequest' => "KnowledgeRequest")

request['Ocp-Apim-Subscription-Key'] = accessKey
request.content_type = "multipart/form-data; boundary=batch_" + batchNumber  
request.body = post_body.join


# Send the request and get the response.
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end

puts "\nRelevant Headers:\n\n"
response.each_header do |key, value|
    # Header names are lower-cased.
    if key.start_with?("bingapis-") or key.start_with?("x-msedge-") then
        puts key + ": " + value
    end
end

puts "\nJSON Response:\n\n"
puts JSON::pretty_generate(JSON(response.body))

Ruby result is empty, but C# example online works:

https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/quickstarts/csharp

  "tags": [
    {
      "displayName": "",
      "actions": [
        {
          "actionType": "MoreSizes"
        },
        {
          "actionType": "ImageById"
        }
      ]
    }
  ],
  "image": {
    "imageInsightsToken": ""
  }
ruby image rest post bing
1个回答
0
投票

在回顾Ruby的Net::HTTP类时,我发现了一个reference,它说使用Net::HTTP#post_form来表示多部分表单数据。我会尝试重构您的代码以使用此方法填充表单正文,而不是直接将其设置为字符串值。在直接设置帖子正文时,可能是您的表单数据未正确读取。

© www.soinside.com 2019 - 2024. All rights reserved.