Reputation: 343
So I am using Multi-part gem to upload multi-part form data. And I have arrays including file paths, file names and file types.
Since I want to upload multiple files, I use .each
to loop through those arrays and try to construct some commands like
"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')
And here is my try:
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)
And it will give me error msg:
syntax error, unexpected tASSOC, expecting keyword_end
fileorder => UploadIO.new(File.new(value)...syntax error, unexpected ',', expecting keyword_end ...etype[value], filename[value]),
syntax error, unexpected tASSOC, expecting keyword_end
lastfile => UploadIO.new(File.new(value)...
Upvotes: 0
Views: 354
Reputation: 4516
I will point you in the right direction since it will take me a while to set up everything to make your code work.
First you have a syntax error so I would recommend you install a plugin/extension for your editor that checks the syntax for your code when you save the file. (I know from experience that your error message is a syntax error, but the plugin showed me where exactly it happens).
Second you can't do the dynamic computation you want in Ruby so you have to first build the hash and then pass it as an argument:
Try something along these lines:
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)
Upvotes: 1