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

时间:2019-02-14 17:48:01

标签: ruby image rest post bing

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

Post主体中的文本边界必须包含在图像数据中。我知道查询有效,因为我可以使用C#或Java发送相同的请求并获得结果。我已经尝试对图像数据进行base64编码,然后将文件读入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结果为空,但在线C#示例有效:

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

  "tags": [
    {
      "displayName": "",
      "actions": [
        {
          "actionType": "MoreSizes"
        },
        {
          "actionType": "ImageById"
        }
      ]
    }
  ],
  "image": {
    "imageInsightsToken": ""
  }

1 个答案:

答案 0 :(得分:0)

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