environment ruby2.6.5 rails5.2.4 gem 'carrierwave' gem 'fog-aws'
If the posted file name contains Japanese, subsequent processing will be difficult. With gem'carrierwave', you can rename the file as officially stated, so let's start from there. In my case, I decided to save the filename as a random alphanumeric character. Don't use the current time when saving. When resizing, the time will be off and an error will occur.
image_uploader.rb
def filename
"#{secure_token}.#{file.extension}" if original_filename.present?
end
def secure_token
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end
By writing in this way, the posted file name will be saved in random alphanumeric characters. Although the file name was changed with only filename, access to S3 did not work, but it was solved by adding def secure_token.
routes.rb
resources :posts do
member do
get :download
end
end
posts_controller.rb
def download
url = URI.encode(@post.image.url)
data_path = open(url)
send_data data_path.read, disposition: 'attachment',
type: @post.image_type
end
Since my level is a beginner level, I think there is a waste in the description, but please forgive me.
When the file name first contained a Japanese name, there was nothing wrong with uploading. However, when I wrote the download method and tried to download it, 502 access denied was displayed. This 502 is awkward and at first I thought I didn't have access to AWS, but if I could upload it, I should have access. Further investigation reveals that 502 is displayed even if the URL is not found, Furthermore, it turned out that the cause was the Japanese notation. This is probably the reason why the files are often random alphanumeric files when downloaded on image posting sites.
Recommended Posts