I am making a script and it uses the
on open {dropped_item}
end open
The thing is i only want the drooped item to be one file and contain certain endings…
Is their any way to do checks for this?
I am making a script and it uses the
on open {dropped_item}
end open
The thing is i only want the drooped item to be one file and contain certain endings…
Is their any way to do checks for this?
Here is some code that shows a way to impose those limitations:
on run
-- This is a way to test "on open" handlers without actually having to drag and drop files. Leave it out of the finished app, or keep it (without the try block) to let user choose files if they double click the app instead of dropping files on it.
try
open (choose file with multiple selections allowed)
on error m number n
return {"ERROR", n, m}
end try
end run
property allowed_suffix_list : {".pdf", ".html", ".txt", "2009.rtf"}
on open dropped_items
if length of dropped_items is not equal to 1 then
display dialog "Files may only be dropped on this script one at a time." with title "Droplet Error" with icon stop buttons {"Cancel"} default button 1
-- The error thrown by the Cancel button will prevent further evaluation.
end if
set dropped_item to first item of dropped_items
if length of allowed_suffix_list is 0 then error "Script error: no endings in the allowed list!"
set item_info to info for dropped_item without size
set verified_suffix to missing value
repeat with allowed_suffix in allowed_suffix_list
set allowed_suffix to contents of allowed_suffix -- dereference implicit reference created by repeat with . in . loop.
if name of item_info ends with allowed_suffix then
set verified_suffix to allowed_suffix
exit repeat
end if
end repeat
if verified_suffix is missing value then
-- Format suffix list for error message.
set otid to text item delimiters
set text item delimiters to {return & tab}
set formatted_suffix_list to {""} & allowed_suffix_list as Unicode text
set text item delimiters to otid
-- Issue error message.
display dialog "Dropped file name is " & name of item_info & ". The file must have one of the following endings:" & formatted_suffix_list with title "Invalid Filename Ending" with icon stop buttons {"Cancel"} default button 1
-- The error thrown by the Cancel button will prevent further evaluation.
end if
-- Only one item was dropped (dropped_item), and it has one of the approved extensions. Put other processing here.
end open
Since you said “ending” and not “extension”, I went with the broader concept of a suffix. The code could be a bit simpler if you only wanted to check actual extensions (the part after the last dot).