在RoR中创建CKAN资源,以字符串形式提供文件内容

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

如何在RoR中创建CKAN资源,提供包含文件内容的字符串?

这似乎是一个有效的命令行解决方案(如果我将文件保存到文件系统):

curl -H 'Authorization: <api_key>' 'https://demo.ckan.org/api/action/resource_create' --form [email protected] --form package_id=<pck_id>

鉴于我将CSV文件内容作为字符串,我如何将其上传到CKAN网站?

这是我现在的代码,资源已创建,但其内容似乎为空白。

    http_client = HTTPClient.new

    temp_file = Tempfile.open('csv_export_tmp_file')
    temp_file.write(resource_content)

    body = {
      name: <filename>,
      title: <filetitle>,
      package_id: <package_id_here>,
      description: <description>,
      created: <created_at_time>,
      upload: temp_file,
      mimetype: 'text/csv',
      resource_type: 'file',
      format: 'csv'
    }
    response = http_client.post(resource_create_url, body, [['Authorization', api_key], ['Content-Type', 'multipart/form-data']])

    temp_file.close
    temp_file.unlink
ruby-on-rails jruby ckan
1个回答
0
投票

这是我最终使用的解决方案

    resource_create_url = 'ckan_site_url.com/api/action/resource_create'

    http_client = HTTPClient.new

    extended_string_io = Class.new(StringIO) do
      def path
        'data.csv'
      end
    end

    virtual_file = extended_string_io.new("my, csv, file, content\n1,2,3,4")

    body = {
      name: <filename>,
      title: <filetitle>,
      package_id: <package_id_here>,
      description: <description>,
      created: <created_at_time>,
      upload: virtual_file,
      resource_type: 'file',
      format: 'csv'
    }
    response = http_client.post(resource_create_url, body, [['Authorization', api_key]])
© www.soinside.com 2019 - 2024. All rights reserved.