0

In my Ruby application, I have a file upload that I've set up with AWS. When displaying uploaded files back to the user, I would like to display only the name of the uploaded file, not the entire file.

In my view, I'm using:

<td>
    <%= link_to file.file_url.split('/').last, file.file_url, target: '_blank' %>
</td>

Which outputs something like File_name.pdf instead of https://bucket_name.s3-us-west.../file_name.pdf, which is exactly what I need.

However, for certain file uploads, there are parameters appended to the file name, so I get something like File_name.pdf?AWSAccessKeyID=1234&Expires=1234. When displayed in a view, that looks ugly as hell.

I would like to split file URL string at the last trailing slash, and then again at the "?". I've tried slash and chomp but can't seem to format it correctly. Is that the appropriate approach?

2 Answers 2

3

You should probably create a helper which will take file.file_url and convert it to "File_name.pdf", it will look like this:

def aws_file_name(url)
  uri = URI.parse(url) # =>  #<URI::HTTPS https://bucket_name.s3-us-west/.../File_name.pdf?AWSAccessKeyID=1234&Expires=1234>
  File.basename(uri.path) # => "File_name.pdf"
end

Then:

<%= link_to aws_file_name(file.file_url), file.file_url, target: '_blank' %>
Sign up to request clarification or add additional context in comments.

Comments

0

new_str = str.slice(0..(str.index('?'))) will cut the filename after the first occurence of ?
where str is your current filename and new_str will be the cut version.

//edit
new_str will still contain the ?
if you don't want this to happen then try using new_str = str.split('?')[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.