name of the file

hiya, how can i get the name of a file or folder dropped onto a control? it’s a doddle in vanilla applescript but is driving me nuts in AS.

Thanks in advance,

P

To receive a drop you need to have at minimum two handlers connected to the object. The first is used to declare the file types for the drop. I prefer to use the awake from nib handler of the object. The second required handler is the drop handler itself. The data collected by a drop is actually a list of all the things dropped, so you need to add in a little code to make sure your only handling the first object… unless you want a list, in which case you’ll need to write code to cycle through each item.

Assuming that you have a text field named “textField” and a window named “window” that you’re using to collect and display the drag info… this will collect the item dropped on the text field and display either the path or the file name of the object dropped (see comments in code).

on awake from nib theObject
	if name of theObject is "textField" then
		tell theObject to register drag types {"file names"}
	end if
end awake from nib

on drop theObject drag info dragInfo
	set dataTypes to types of pasteboard of dragInfo
	if "file names" is in dataTypes then
		(* Get the list of files *)
		set preferred type of pasteboard of dragInfo to "file names"
		set thePaths to contents of pasteboard of dragInfo
		set preferred type of pasteboard of dragInfo to ""

		(* Get the first file and display in the field *)
		set theFile to item 1 of thePaths --> Shows the file path
		-- set theFile to name of (info for POSIX file theFile) --> Uncomment to show only the file name
		set contents of text field "textField" of window "window" to (theFile as string)
	end if
end drop

j

this was the bit i was missing:

– set theFile to name of (info for POSIX file theFile) → Uncomment to show only the file name

thanks a million job - really appreciate the help!!

Cheers,
Mr_Wickedness

I am trying to do the same thing. I tried the above and when I try to drag and drop a file into the text field, the file just springs back to where I took it from and nothing else happens. I just made a text field and put it in on the window and then put the code in the default script that is made when you start a new project.
I’m a newbie in case you can’t tell. :smiley: