rails4 upload file extension error ActionDispatch::Http::UploadedFile - actiondispatch

Guy
now i want to upload file with rails 4
my problem now i can't check the file extension before upload it
Note : I can upload the file well but i want to get the file kind before upload it
because i need the extension in another step in my App.
I'm tried to use the commands
File.extname(params[:Upload])
but always got the error
can't convert ActionDispatch::Http::UploadedFile into String
also how i can get the file base name before upload it ??
when i tryed to use
File.basename(params[:Upload])
i got the same error
can't convert ActionDispatch::Http::UploadedFile into String
also when i tried to convert the name to Sting i don't get any thing

That's because File.extname expects a string file name, but an uploaded file (your params[:upload] is an object, it's an instance of the ActionDispatch::Http::UploadedFile class (kind of a temporary file)
To fix the problem you need to call the path property on your params[:upload] object, kind of like that
File.extname(params[:Upload].path)
Btw, if you're trying to get the type of the uploaded file, I'd encourage you to check for the params[:Upload].content_type instead, it's harder to spoof

You can use this:
params[:Upload].original_filename.split('.').last
The original_filename contains full filename with extension.
so you split it based on '.' and last index will contain the file extension.
For Example:
"my_file.doc.pdf".split('.').last # => 'pdf'
You can check this for more info ActionDispatch::Http::UploadedFile.

Related

Apache Beam/Dataflow- passing file path to ReadFromText

I have a use case where I want to read the filename from a metadata table, I have written a pipeline function to read the metadata table, but I am not sure how can I pass this information to ReadFromText as it only takes string as input, Is it possible to assign this value to ReadFromText(). Please suggest some workarounds or ideas how to achieve this, Thanks
code: pipeline | 'Read from a File' >> ReadFromText(I want to pass the file path here?,
skip_header_lines=1)
Note: There will be various folders and files in storage, files are in csv format, but in my use case I can't directly pass the storage location or filename to file path in ReadFromText. I want to read it from metadata and pass the value. Hope I am clear, Thanks
I don't understand why you need to read the metadata. If you want to read all the files inside a folder, you can just provide a blob. This solution working in python, not sure about java.
p|readfromtext("./folder/*.csv")
"*" is the blob here, which allows pipeline to read all the patterns matching .csv. You can also add something at the starting.
What you want is textio.ReadAllFromText which reads from a PCollection instead of taking a string directly.

pydrive: Losing file content during upload()

I currently have a 34x22 .xlsx spreadsheet. I am downloading it via pydrive, filling in some of the blank values, and uploading the file back via pydrive. When I upload the file back, all cells with formulas are blank (any cell that starts with =). I have a local copy of the file I want to upload, and it looks fine so I'm pretty sure the issue must be with pydrive.
My code:
def upload_r1masterfile(filename='temp.xlsx'):
"""
Upload a given file to drive as our master file
:param filename: name of local file to upload
:return:
"""
# Get the file we want
master_file = find_r1masterfile()
try:
master_file.SetContentFile(filename)
master_file.Upload()
print 'Master file updated. ' + str(datetime.datetime.now())
except Exception, e:
print "Warning: Something wrong with file R1 Master File."
print str(e)
return e
The only hint I have is that if I add the param={'convert': True} tag to Upload, then there is no loss. However, that means I am now working in google sheets format, and I would rather not do that. Not only because it's not the performed format to work with here, but also because if I try to master_file.GetContentFile(filename) I get the error: No downloadLink/exportLinks for mimetype found in metadata
Any hints? Is there another attribute on upload that I am not aware of?
Thanks!
Robin was able to help me answer this question at the github repository. Both suggested solutions worked:
1) When you upload the file, did you close Excel first? IIRC MS Office writes a lot of the content to a temporary file, so that may explain why some parts are missing. If you tried the non converting upload first, the full file may have been saved to disk between the two tries, and thus the second converting upload attempt worked.
2) GetContentFile takes a second argument called mimetype, which should allow you to download the file. Could you try .GetContentFile(filename, mimetype="application/vnd.ms-excel")? If that mimetype doesn't work as anticipated, there is a great StackOverflow post here which lists a bunch of different types you can try.
Thanks again Robin!

Validation for file type

Am using Carrierwave gem to upload the file.
I need to validate the file while uploading ,it should accept only pdf,jpg and png.
Is there solution to do clientside validation.
The HTML input element has an accept attribute you can use to filter by file type. http://www.w3schools.com/tags/att_input_accept.asp
You can also validate by file extension using something like http://jqueryvalidation.org/extension-method/
This does not prevent a malicious user from uploading a different file type than intended, so you should still validate it after uploading using something like https://github.com/carrierwaveuploader/carrierwave/blob/master/lib/carrierwave/processing/mime_types.rb

How to get the file-name before downloading the file

I am trying to download a binary file from a http: server. I am using the functions InternetOpenUrl() and then InternetReadFile() to download the file. Is it possible to know the file name before downloading?
What I am doing now to get the file name is- Once the download is complete, using GetFileVersionInfo() and from the buffer i am getting the OrginalFilename, then renaming the file to the OrginalFilename.
Is there any other way to get the file name before downloading?
Thanks
Vinod
Look at HttpQueryInfo. Look at the Content-Type and Content-Disposition headers.
You may have to use HTTP_QUERY_CUSTOM to get raw content-type if it just returns e.g. "text/plain".
To get all the headers (and thereby work out which one contains the information you want) you can use HTTP_QUERY_RAW_HEADERS_CRLF.

How to download file from aws s3 using python without using key

I need to download an xml file from AWS-S3.
I tried using get_contents_to_filename(fname) , it worked.
But i need to download the file without specifying fname, because if i specify the fname my downloaded file gets saved tofname.
I want to save the file as it is, with its name.
this is my current code
k = Key(bucket)
k.set_contents_from_filename(fname)
can someone please help me to download and fetch the file without using key.
Thanks in advance!
I'm not sure which library you're using, but if k is the AWS key you want to download, then k.name is probably the key name, so k.get_contents_to_filename(k.key) would probably do more or less what you want.
The one problem is that the key name might not be a legal file name, or it may have file path separators. So if the key name were something like '../../../../somepath/somename' the file would be saved somewhere you don't expect. So copy k.name to a string and either sanitize it by changing all dangerous characters to safe ones, or just extract the part of the key name you want to use for the file name.