How encoded filename in S3 Presigned url in ruby - ruby

in S3 presigned url how I can encoded the string $filename
s3.bucket(ENV.fetch('S3_BUCKET_NAME')).presigned_post(
key: "uploads/#{Time.now.to_i}/${filename}",
allow_any: ['authenticity_token'],
acl:'public-read',
metadata: {
'original-filename' => '${filename}'
},
success_action_status: "201"
)
sometime the filename include some special char or spaces. I would like to avoid them in the key

To cast your filename to url-safe form you may use 2 options:
If you are using Rails you may try to use .parameterize method. See
https://apidock.com/rails/String/parameterize
If you are using plain Ruby:
filename.gsub(%r{\s}, '_').gsub(%r{[^a-zA-Z0-9-.]+}, '')
Sample:
'asf asfa 1-240((($#))!#.jpeg'.gsub(%r{\s}, '_').gsub(%r{[^a-zA-Z0-9-.]+}, '')
=> "asfasfa1-240.jpeg"
Both approaches should throw away any spaces and special characters.

Related

Put text on transfer.sh/file.io from ruby

I'm trying to upload text (not a file) to transfer.sh (edit: and file.io/0x0.st) from ruby. All services only give curl examples but not anything for programming languages. I tried
puts HTTParty.post(
'https://transfer.sh/',
multipart: true,
body: { file: 'some text' }
).body.inspect
but that just gives me an empty string as result, not the url where I should find the upload.

File.new command for Ruby to upload mp3 file to soundcloud

I'm now trying to upload a mp3 file to Soundcloud. Here I'm bogged down to the use of File.new command in Ruby.
I send a request and a passing parameter looks like the below.
Parameters: {..."mp3_1"=>#<ActionDispatch::Http::UploadedFile:0x007ff24d5e3ea8 #tempfile=#<Tempfile:/var/folders/kk/y_wprlln2qv6mzylj03g14x00000gn/T/RackMultipart20160316-21426-14vu8x1.mp3>, #original_filename="datasecurity.mp3", #content_type="audio/mp3", #headers="Content-Disposition: form-data; name=\"mp3_1\"; filename=\"datasecurity.mp3\"\r\nContent-Type: audio/mp3\r\n">}
Then, I write File.new command with the potentail file name and params[:mp3_1] like the below.
client = Soundcloud.new(:access_token => 'XXX')
track = client.post('/tracks', :track => {
:title => 'This is my sound',
:asset_data => File.new("file name",params[:mp3_1])
})
Now I get an error saying:
no implicit conversion of ActionDispatch::Http::UploadedFile into String
The paperclip function works ( storing file to the storage directly has been what I've done ) but this file.new doesn't allow me to move forward. If I can get any help, I really appreciate that (:
Best
you already have a file, no need to create a new one with File.new
have a closer look to your dump :
#tempfile=#<Tempfile:/var/folders/...../RackMultipart20160316-21426-14vu8x1.mp3
this is a file, you may use it directly in your call
client.post('/tracks', :track => {
:title => 'This is my sound',
:asset_data => params[:mp3_1].tempfile)
})

I always get an UndefinedConversionError in Ruby 2.0 while scraping with Mechanize

When I try to submit a textarea with Mechanize and Ruby 2.0, I always get an
Encoding::UndefinedConversionError: U+0151 from UTF-8 to ISO-8859-1
Then I tryied to convert the text with Iconv, I got a similar result:
Iconv.iconv("LATIN1", "UTF-8", text)
I get this error message:
Iconv::IllegalSequence: "őzködik, melyet "...
As the text contains east-european characters. What can I do to avoid this kind of inconveniences or how can I convert properly between different encodings?
I have found an elegant solution:
replacements = [["À", "À"], ["Á", "Á"], ["Â", "Â"], ["Ã", "Ã"], ["Ä", "Ä"], ["Å", "Å"], ["Æ", "Æ"], ["Ç", "Ç"], ["È", "È"], ["É", "É"], ["Ê", "Ê"], ["Ë", "Ë"], ["Ì", "Ì"], ["Í", "Í"], ["Î", "Î"], ["Ï", "Ï"], ["Ð", "Ð"], ["Ñ", "Ñ"], ["Ò", "Ò"], ["Ó", "Ó"], ["Ô", "Ô"], ["Õ", "Õ"], ["Ö", "Ö"], ["Ø", "Ø"], ["Ù", "Ù"], ["Ú", "Ú"], ["Û", "Û"], ["Ü", "Ü"], ["Ý", "Ý"], ["Þ", "Þ"], ["ß", "ß"], ["à", "à"], ["á", "á"], ["â", "â"], ["ã", "ã"], ["ä", "ä"], ["å", "å"], ["æ", "æ"], ["ç", "ç"], ["è", "è"], ["é", "é"], ["ê", "ê"], ["ë", "ë"], ["ì", "ì"], ["í", "í"], ["î", "î"], ["ï", "ï"], ["ð", "ð"], ["ñ", "ñ"], ["ò", "ò"], ["ó", "ó"], ["ô", "ô"], ["õ", "õ"], ["ö", "ö"], ["ø", "ø"], ["ù", "ù"], ["ú", "ú"], ["û", "û"], ["ü", "ü"], ["ý", "ý"], ["þ", "þ"], ["ÿ", "ÿ"]]
def replace(str,replacements)
replacements.each {|replacement| str.gsub!(replacement[0], replacement[1])}
return str
end
my_string=replace(my_string,replacements)

How to save a html5 canvas.toDataURL as a png file on the server using Seaside

I have an image that users can annotate on the browser. I can access the image using
canvas.toDataURL()
...I'd like to add a 'save' option for the user to save the image on the server.
This question has been answered for php...
file_put_contents('test.png', base64_decode(substr($data, strpos($data, ",")+1)));
...what I need is a Seaside callback with the PNG file content.
Is there a way to do this in Seaside?
Johan pointed out that the mine type declaration has to be removed from the value string. This works in VW... (with string hack to remove 'data:image/png;base64,')
html jQuery ajax
callback: [:value |
| writestream string |
writestream := ('c:\data\sketchpad_image.png' asFilename withEncoding: #binary) writeStream.
string := value copyFrom: 23 to: value size.
[writestream nextPutAll: (Seaside.GRPlatform current base64Decode: string) asByteArray]
ensure: [writestream close] ]
value: (Javascript.JSStream on: 'sketchpadCanvas.toDataURL()')
Depending on how you want your website to behave, I guess there are multiple ways of doing it. Here is the raw sample of one possibility I can think of using a jQuery ajax callback:
html jQuery ajax
callback: [:value | (FileStream newFileNamed: 'test.png')
nextPutAll: (value copyFrom: ((value indexOf: $,) + 1 to: value size) base64Decoded ]
value: (JSStream on: 'canvas.toDataURL()')
I did not test this myself. Maybe the filestream needs to be sent the #binary message to make a correct png file. Let me know if there are troubles.
Hope it helps.
Does the file-upload section in the Seaside book solve your problem? Taking the code from the book:
UploadForm>>renderContentOn: html
html form multipart; with: [
html fileUpload
callback: [ :value | self receiveFile: value ].
html submitButton: 'Send File' ]
UploadForm>>receiveFile: aFile
| stream |
stream := (FileDirectory default directoryNamed: 'uploads')
assureExistence;
forceNewFileNamed: aFile fileName.
[ stream binary; nextPutAll: aFile rawContents ]
ensure: [ stream close ]
I've also published a blog post about how to manage file uploads in a production environment using Seaside and Nginx that may be of interest.

Escape forward slash in Ruby url helper

Setuping a staticMatic project using /index.html:
#slug = current_page.gsub(/\.html/, '')
returns "/index(.html)", but should be /index
Changing term corrects: - #slug = current_page.gsub("/", "").gsub(".html", "") as found in:
https://github.com/adamstac/staticmatic-bootstrap/blob/master/src/helpers/application_helper.rb
To delete the beginning "/" after you've stripped the html simply execute this (which will do both in one command):
current_page.gsub(/\.html/, '').gsub(/\//,''))

Resources