My users are submitting files that should be passed on to a third party.
The files are submitted as params[:files]:
= form_with :url => files_path, :method => :create, :multipart => true do
= file_field_tag "files[]", :multiple => true
From my controller, they look like this:
[#<ActionDispatch::Http::UploadedFile:0x0000000103c1c678 @tempfile=#<Tempfile:/var/folders/k7/n71v0f_n2nb3pzyj38s5y9x80000gn/T/RackMultipart20220902-12314-in3y4h.txt>, @original_filename="test.txt", @content_type="text/plain", @headers="Content-Disposition: form-data; name=\"files[]\"; filename=\"test.txt\"\r\nContent-Type: text/plain\r\n">]
I go through the files like this:
params[:files].each do|file|
HTTParty.post(
"https://example.com/files",
headers: {
"Accept" => "application/json",
"Content-Type" => "multipart/form-data"
},
body: {
"file" => File.open(file.tempfile)
}
)
end
Even though the files have a file.original_filename property, the one submitted in my POST request is the randomly temporary one. In this example RackMultipart20220902-12314-in3y4h.txt. Here is a trimmed log from my request:
<- "POST /files HTTP/1.1\r\nAccept: application/json\r\nContent-Type: multipart/form-data; boundary=------------------------dnh46jyEwRV85_DO\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: example.com\r\nContent-Length: 433\r\n\r\n"
<- "--------------------------dnh46jyEwRV85_DO\r\nContent-Disposition: form-data; name=\"file\"; filename=\"RackMultipart20220902-12314-in3y4h.txt\"\r\nContent-Type: text/plain\r\n\r\nhello\r\n--------------------------dnh46jyEwRV85_DO\\r\n"
-> "HTTP/1.1 200 OK\r\n"
This means that the original file names are lost between me and the third party. How can I change that?
original_filenameis the correct way to go. However, you are seeing a temporary file because you triggered the HTTP request via HTTParty API client, and not the upload form in the UI.I see the upload has
User-Agent: Ruby. In that case, you get the filename that HTTParty generated when loaded the file in memory as tempfile.Try to upload it from the form UI, and you will get the original filename from your disk.