我可以使用循环通过multipart :: post gem上传多个文件

时间:2017-08-24 19:44:19

标签: ruby-on-rails multipart

所以我使用link gem来上传多部分表单数据。 我有数组,包括文件路径,文件名和文件类型。

由于我想上传多个文件,我使用.each循环遍历这些数组,并尝试构建一些命令,如

"file1" => UploadIO.new(File.new('/tmp/1.jpg'), 'image/jpeg', '1.jpg'),
"file2" => UploadIO.new(File.new('/tmp/2.jpg'), 'image/jpeg', '2.jpg'),
"file3" => UploadIO.new(File.new('/tmp/3.jpg'), 'image/jpeg', '3.jpg')

这是我的尝试:

filepath = ['/tmp/1.jpg','/tmp/2.jpg','/tmp/3.jpg']
filetype = ['image/jpeg','image/jpeg','image/jpeg']
filename = ['1.jpg','2.jpg','3.jpg']

require 'net/http/post/multipart'
    url = URI.parse("https://example.com/api/send")
    req = Net::HTTP::Put::Multipart.new url.path,
        filepath.each_with_index do |(key, value),index|
            fileorder = "file" + (key+1).to_s
            lastfile = "file"+ (filepath.size).to_s 
            fileorder => UploadIO.new(File.new(value), filetype[value], filename[value]),
            if index == filepath.size - 1
                lastfile => UploadIO.new(File.new(value), filetype[value], filename[value])
            end
        end
    req.basic_auth("username", "password")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = (url.scheme == "https")
    res = http.request(req)

它会给我错误消息:

  

语法错误,意外的tASSOC,期待keyword_end
                                      fileorder => UploadIO.new(File.new(值)...

     

语法错误,意外',',期待keyword_end   ... etype [value],filename [value]),

     

语法错误,意外的tASSOC,期待keyword_end

     

lastfile => UploadIO.new(File.new(值)...

1 个答案:

答案 0 :(得分:1)

我会指出正确的方向,因为我需要一段时间来设置所有内容以使代码正常工作。

首先你有一个语法错误所以我建议你为编辑器安装一个插件/扩展,在你保存文件时检查代码的语法。 (我从经验中知道您的错误消息是语法错误,但插件显示了我发生的确切位置)。

其次,您不能在Ruby中进行所需的动态计算,因此您必须先构建哈希,然后将其作为参数传递:

尝试以下几点:

url = URI.parse("https://example.com/api/send")

files = {}
filepath.each_with_index do |(key, value),index|
  # ... calculate your values
  files["file#{index}"] = UploadIO.new(File.new("./#{key}.#{value}"), "image/jpeg", "#{key}.#{value}")
  # {} will become { "file1" => UploadIO.new(File.new("./image.jpg"), "image/jpeg", "image.jpg") }
end

# "files" hash will be something like this
# {
#   "file1" => UploadIO.new(File.new("./image1.jpg"), "image/jpeg", "image1.jpg"),
#   "file2" => UploadIO.new(File.new("./image2.jpg"), "image/jpeg", "image2.jpg"),
#   "file3" => UploadIO.new(File.new("./image3.jpg"), "image/jpeg", "image3.jpg")
#}
req = Net::HTTP::Put::Multipart.new(url.path, files)

req.basic_auth("username", "password")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
res = http.request(req)