How to access paperclip attachments on server side? - ruby-on-rails

I am using paperclip to attach an excel file to a mode.
The purpose is to import the data from the excel file to the database.
Model: Import
has_attached_file: spreadsheet
For the import process, I want to access the file in my model as following.
path = "#{Rails.root}/public/#{spreadsheet.url}"
This doesn't work. I guess because the url has the timestamp at the end.
In general what is the best way to access the attachments on server side ?

I think you're looking for the to_file method. You should be able to do something like this:
excel_file = self.spreadsheet.to_file
which will either return the uploaded file from the server (if you're using s3 or remote storage), or if it has been assigned to the model but not actually stored yet (if you haven't called model.save since it was uploaded), it returns the temp file stored on disk.
From there you should be able to use an excel gem or library to parse the contents.
Alternatively, you can use spreadsheet.url(nil, false) - the second parameter denotes whether or not to append a timestamp.

#spreadsheet.path
http://rdoc.info/gems/paperclip/2.3.8/Paperclip/Attachment#path-instance_method

Related

How to zip and save jSON data received from an API with Rails

So, I'm creating an app that works like a bot, it makes a call to an API from time to time, then it receives a response in a json-like format and saves it like this:
finalResult = RestClient.get( apiUrl, headers = apiHeaders )
jsonData = JSON.parse(ActiveSupport::Gzip.decompress(finalResult))
time = Time.now
File.write("public/#{time}.json", jsonData)
I'm using ActiveSupport to be able to parse this Gzip compressed data, since it's a lot of data, otherwise it takes forever to get it. Then I get the time the data was received, basically, and I use it to name the file so that I can keep good track of it.
What I need to do now is compress this .json file, if possible, into a .zip file(it can be .rar, or .7z, or .tz, whatever) before I upload it to my storage so it takes less space. Is there anyway that I can do something similar to File.write but to save it as a zipped json file? I already checked stuff like zlib and ruby-zip, but they only let me zip files that already "exist", so I can't save it as a zipped .json directly, I'd need to take the .json file and then zip it, but how could I do that if the name of the file is a Time.now and it always change?
I'd appreciate any help, thanks in advance :)
EDIT¹
Giving some more details that may help you to help me:
I created a controller and model to handle this, since I'll be using ActiveStorage. It's ResponsesController and Response model, and the only parameter that the Response model has is has_one_attached :json_file. I intend to use Heroku to handle the CRON job of calling the API and I'll upload the .json files(or .zip files) to an AWS storage.

upload a file(.pdf, .jpg etc) using rails active storage via API through postman? (not through rails views)

I saw N number of tutorials on uploading a file to active storage locally, to S3 etc using rails view. But I cannot find a legit source on how to upload a file to an active storage through API Say via postman, like what are prerequisites required to pass an attachment through API via postman?
Let me detail it.
Step 1: Through React or any frontend framework, I will choose a file to upload(a .PDF file), ultimately it should be saved somewhere.
Step 2: This chosen file should be passed through as API to the backend service where the storage of the chosen file to be saved in a storage like AWS S3.
How will the API request be sent to store the file? Can someone help me out with it?
its Very Simple to Do
Open the Postman
Go to Body -> Form-data
after that take a mouse to the key filed you will find Option for File
Then you have to select the file and send the request
Or send the File Path in the raw JSON object as well like this
and then Create the Object at backend so place check on file object if it blank then send path like this
// For Temporary Use Over Back End Only NOT NEED To Send These
"file_path" : "/home/jolly/Downloads/pdf/pdf-5.pdf",
"file_name" : "pdf-5.pdf"
and then in the code use it to create the file object which u pass where u needed to save s3 or rails storage
file_path = params[:file_path]
file_name = params[:file_name]
image_path = Rails.root+file_path
image_file = File.new(image_path)

How to determine if file has changed on the S3 bucket from a mobile client (e.g. iOS)

Is it possible to use AWSS3TransferManager or an alternative class to determine if a file has changed on the s3 server before downloading it?
Ideally I'd like to have some sort of automatic function that takes into account automatically the following:
File size
File type
File name
or:
File content data analysis (some sort of signature based on bit content)
Alternatively:
I see that it is possible to get the modification date for an s3 bucket, however I am not sure how this works in iOS.
If you want to download the file like the AWSS3TransferManager download method, you can use the alternative class AWSS3GetObjectRequest / AWSS3GetObjectOutput.
If you do not want to download the file, you can use AWSS3HeadObjectRequest / AWSS3HeadObjectOutput that will return the object's metadata or "head" of the file.
The value: lastModified will be in the AWSS3...ObjectOutput value for both class responses.

Finding file type of NSData recieved from server

I am receiving a text file from a socket over TCP/IP. There is no file extension (or filename for that matter) as the data is received as bytes. I can take the data from this (in the form of NSData) and load it into a UITextView and display it fine.
I want to persist this data to a file. However, I don't know what format the data is in (txt, rtf, doc, docx)? I assume it as .txt and save it in the documents directory, but is there a programmatic way of finding out for sure? I've looked around StackOverflow and at the documentation and haven't been able to find anything.
And is there a way to get the details of the file attributes like the file creation date.
Thanks in advance.
When you send a file over a TCP/IP connection, only the file contents will be converted to data and be passed across. If you want the filename,extension and the file attributes, then you will have to add those details separately and append it with the data to be sent. Then you can parse it at the receiver end and use the results inside your app.
You can choose the file type you want when you save the data, you can get attributes from file,please refer to Get file creation date.

How can I identify the kind of file in rackspace?

I gonna upload files to rackspace(video, audio and images) in rails with paperclip or carrierwave, I need to Know the kind of file, to show in the view with image_tag, or video_tag or audio_tag, rackspace tell me the kind of file? or I have to store in my database? thanks
You can query/set the file type by using the 'content_type' function located in the 'ruby-cloudfiles' library.
See here: https://github.com/rackerlabs/ruby-cloudfiles/blob/master/lib/cloudfiles/storage_object.rb#L80-L82
Something like this should work for creating the object:
container = conn.create_container('new_container')
obj = container.create_object('new_obj.txt')
obj.load_from_filename('./obj.txt')
obj.content_type = 'text/plain'
And to retrieve the object:
obj = container.object('new_obj.txt')
puts obj.content_type # text/plain
Even if rackspace would tell you the file type, you don't want it to, since it would take so long to run roundtrips from your server to theirs.
My code examples below assume carrierwave, but I'm sure paperclip has similar options. Two options:
Interpret the file extension
Something like: File.extname(user.avatar), which you then have to interpret however you like.
Record & interpret the mime type.
The carrierwave readme explains how to get carrierwave to calculate it in the first place, and then you should probably store it to your database manually or using carrierwave-meta. Then user.avatar.content_type would be something like image/jpeg which you could easily interpret as a particular file type.

Resources