以下代码包括来自
https://macosxautomation.com/applescript/sbrt/sbrt-08.html的3个encoding routines
创建 URL 时的标准做法是
将特殊字符(高级 ASCII)和空格编码到它们的
十六进制等价物。例如,URL 中的空格被转换
收件人:%20
脚本:
tell application "Finder"
set sel to (the POSIX path of (the selection as alias))
set sel to ((characters 10 thru -1 of sel) as string)
set sel to "afp://myserver._afpovertcp._tcp.local/" & my encode_filepath(sel, true, false)
set the clipboard to sel
end tell
-- this sub-routine encodes special characters in a filepath:
-- My Disk:My Folder:My File.htm
-- My%20Disk:My%20Folder:My%20File.htm
on encode_filepath(this_file, encode_URL_A, encode_URL_B)
set this_file to this_file as text
set AppleScript's text item delimiters to ":"
set the path_segments to every text item of this_file
repeat with i from 1 to the count of the path_segments
set this_segment to item i of the path_segments
set item i of the path_segments to my encode_text(this_segment, encode_URL_A, encode_URL_B)
end repeat
set this_file to the path_segments as string
set AppleScript's text item delimiters to ""
return this_file
end encode_filepath
-- TEXT ENCODING: encode spaces and high-level ASCII characters (those above 127)
-- encode_URL_A = encode most of the special characters reserved for use by URLs.
on encode_text(this_text, encode_URL_A, encode_URL_B)
set the standard_characters to "abcdefghijklmnopqrstuvwxyz0123456789"
set the URL_A_chars to "$+!'/?;&@=#%><{}[]\"~`^\\|*"
set the URL_B_chars to ".-_:"
set the acceptable_characters to the standard_characters
if encode_URL_A is false then set the acceptable_characters to the acceptable_characters & the URL_A_chars
if encode_URL_B is false then set the acceptable_characters to the acceptable_characters & the URL_B_chars
set the encoded_text to ""
repeat with this_char in this_text
if this_char is in the acceptable_characters then
set the encoded_text to (the encoded_text & this_char)
else
set the encoded_text to (the encoded_text & encode_char(this_char)) as string
end if
end repeat
return the encoded_text
end encode_text
-- encoding high-ASCII characters:
on encode_char(this_char)
set the ASCII_num to (the ASCII number this_char)
set the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
set x to item ((ASCII_num div 16) + 1) of the hex_list
set y to item ((ASCII_num mod 16) + 1) of the hex_list
return ("%" & x & y) as string
end encode_char