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)
})
Related
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.
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.
I am writing a script will perform various tasks with DSV or positional files. These tasks varies and are like creating an DB table for the file, or creating a shell script for parsing it.
As I have idealized my script would receive a "descriptor" as input to perform its tasks. It then would parse this descriptor and perform its tasks accordingly.
I came up with some ideas on how to specify the descriptor file, but didn't really manage to get something robust - probably due my inexperience in ruby.
It seems though, the best way to parse the descriptor would be using ruby language itself and then somehow catch parsing exceptions to turn into something more relevant to the context.
Example:
The file I will be reading looks like (myfile.dsv):
jhon,12343535,27/04/1984
dave,53245265,30/03/1977
...
Descriptor file myfile.des contains:
FILE_TYPE = "DSV"
DSV_SEPARATOR = ","
FIELDS = [
name => [:pos => 0, :type => "string"],
phone => [:pos => 1, :type => "number"],
birthdate => [:pos => 2, :type => "date", :mask = "dd/mm/yyyy"]
]
And the usage should be:
ruby script.rb myfile.des --task GenerateTable
So the program script.rb should load and parse the descriptor myfile.des and perform whatever tasks accordingly.
Any ideas on how to perform this?
Use YAML
Instead of rolling your own, use YAML from the standard library.
Sample YAML File
Name your file something like descriptor.yml, and fill it with:
---
:file_type: DSV
:dsv_separator: ","
:fields:
:name:
:pos: 0
:type: string
:phone:
:pos: 1
:type: number
:birthdate:
:pos: 2
:type: date
:mask: dd/mm/yyyy
Loading YAML
You can read your configuration back in with:
require 'yaml'
settings = YAML.load_file 'descriptor.yml'
This will return a settings Hash like:
{:file_type=>"DSV",
:dsv_separator=>",",
:fields=>
{:name=>{:pos=>0, :type=>"string"},
:phone=>{:pos=>1, :type=>"number"},
:birthdate=>{:pos=>2, :type=>"date", :mask=>"dd/mm/yyyy"}}}
which you can then access as needed to configure your application.
I'm using the (Axlsx gem and it's working great, but I need to add an image to a cell.
I know it can be done with an image file (see Adding image to Excel file generated by Axlsx.?), but I'm having a lot of trouble using our images stored in S3 (through Carrierwave).
Things I've tried:
# image.url = 'http://.../test.jpg'
ws.add_image(:image_src => image.url,:noSelect => true, :noMove => true) do |image|
# ArgumentError: File does not exist
or
ws.add_image(:image_src => image,:noSelect => true, :noMove => true) do |image|
# Invalid Data #<Object ...>
Not sure how to proceed
Try using read to pull the contents into a tempfile and use that location:
t = Tempfile.new('my_image')
t.binmode
t.write image.read
t.close
ws.add_image(:image_src => t.path, ...
To add an alternative answer for Paperclip & S3 as I couldn't find a reference for that besides this answer.
I'm using Rails 5.0.2 and Paperclip 4.3.1.
With image URLs like: http://s3.amazonaws.com/prod/accounts/logos/000/000/001/original/logo.jpg?87879987987987
#logo = #account.company_logo
if #logo.present?
#logo_image = Tempfile.new(['', ".#{#logo.url.split('.').last.split('?').first}"])
#logo_image.binmode # note that our tempfile must be in binary mode
#logo_image.write open(#logo.url).read
#logo_image.rewind
end
In the .xlsx file
sheet.add_image(image_src: #logo_image.path, noSelect: true, noMove: true, hyperlink: "#") do |image|...
Reference link: http://mensfeld.pl/tag/tempfile/ for more reading.
The .split('.').last.split('?').first is to get .jpg from logo.jpg? 87879987987987.
How can I retrieve the file extension of an image while uploading?
I don't have any problems with the upload, just retrieving the files extension , which would be useful when creating thumbnails dynamically.
Thanks
http://codeigniter.com/user_guide/libraries/file_uploading.html
$this->upload->data()
This is a helper function that returns an array containing all of the data related to the file you uploaded. Here is the array prototype:
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[client_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
So after the user has uploaded something, you probably want to store the file extension in your database along with other details about the image :-)
$name_of_file_with_extn = $this->upload->data('file_name')
you can change the item name from the below list
file_name Name of the file that was uploaded, including the filename extension
file_type File MIME type identifier
file_path Absolute server path to the file
full_path Absolute server path, including the file name
raw_name File name, without the extension
orig_name Original file name. This is only useful if you use the encrypted name option.
client_name File name as supplied by the client user agent, prior to any file name preparation or incrementing
file_ext Filename extension, period included
file_size File size in kilobytes
is_image Whether the file is an image or not. 1 = image. 0 = not.
image_width Image width
image_height Image height
image_type Image type (usually the file name extension without the period)
image_size_str A string containing the width and height (useful to put into an image tag)
This might help you.
After you uploaded the file, you can get its property by:
$saved_file_name = $this->upload->data('file_name');
// will give you the filename along with the extension
If you want to get only the file extension before uploading it, use core PHP:
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
or to make it clean
$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);