2013-08-21 49 views
3

在一個Rails應用程序,我需要解析URI的URI編碼不工作

a = 'some file name.txt' 
URI(URI.encode(a)) # works 

b = 'some filename with :colon in it.txt' 
URI(URI.encode(b)) # fails URI::InvalidURIError: bad URI(is not URI?): 

我怎樣才能安全地傳遞一個文件名URI包含特殊字符?爲什麼不在冒號上編碼工作?

回答

0

問題似乎是冒號前面的空格,'lol :lol.txt'不起作用,但'lol:lol.txt'起作用。
也許你可以替換其他東西的空間。

-1

如果你想從給定的字符串中轉義特殊字符。最好使用

esc_uri=URI.escape("String with special character") 

結果字符串是URI轉義字符串,並且可以安全地將它傳遞給URI。 請參閱URI::Escape瞭解如何使用URI轉義。希望這可以幫助。

+0

URI.escape == URI.encode – 7stud

0

使用Addressable::URI::encode

require "addressable/uri" 

a = 'some file name.txt' 
Addressable::URI.encode(Addressable::URI.encode(a)) 
# => "some%2520file%2520name.txt" 

b = 'some filename with :colon in it.txt' 
Addressable::URI.encode(Addressable::URI.encode(b)) 
# => "some%2520filename%2520with%2520:colon%2520in%2520it.txt" 
+0

%2520是一種雙重編碼。 %20是空間的編碼。然後如果你編碼字符串「%20」,「%」符號的編碼是%25,給你「%25」+「20」或「%2520」。您不想對字符串進行雙重編碼。你也需要:gem install addressable。但是也要注意冒號沒有在輸出中編碼。 – 7stud

+0

@ 7stud你是對的..但是這個寶石現在是URI的替代品。而我只是試圖顯示OP可以通過URI來實現什麼不是可以通過使用這個「Addressable」來實現...... :) –

11

URI.escape(或encode)有一個可選的第二個參數。這是一個正則表達式匹配所有應該被轉義的符號。爲了逃避所有非單詞字符,你可以使用:

URI.encode('some filename with :colon in it.txt', /\W/) 
#=> "some%20filename%20with%20%3Acolon%20in%20it%2Etxt" 

有用於encode兩個預定義的正則表達式:

URI::PATTERN::UNRESERVED #=> "\\-_.!~*'()a-zA-Z\\d" 
URI::PATTERN::RESERVED #=> ";/?:@&=+$,\\[\\]" 
+1

更爲一般的方法會做'URI.encode('some filename with:colon in it.txt',Regexp.new(「[^#{URI :: PATTERN :: UNRESERVED}]」))'。在這裏看到更多的細節:http://stackoverflow.com/questions/2834034/how-do-i-raw-url-encode-decode-in-javascript-and-ruby-to-get-the-same-values-在。 –

+0

@kardeiz * + 1 *給你這個信息... –

+0

@kardeiz謝謝,我已經添加到我的答案 – Stefan

1
require 'uri' 

url = "file1:abc.txt" 
p URI.encode_www_form_component url 

--output:-- 
"file1%3Aabc.txt" 


p URI(URI.encode_www_form_component url) 

--output:-- 
#<URI::Generic:0x000001008abf28 URL:file1%3Aabc.txt> 


p URI(URI.encode url, ":") 

--output:-- 
#<URI::Generic:0x000001008abcd0 URL:file1%3Aabc.txt> 

爲什麼不編碼結腸癌的工作?

因爲編碼/轉義被破壞。