使用FileReference对有效字符有约束
Error: Error #2087: The FileReference.download() file name contains prohibited characters.
这很好,因为我认为限制来自底层文件系统
是否存在修剪/替换所有禁用字符的通用方法?
为了清楚起见,我追求的是:
var dirty:String = "Eat this !@##$%%^&&*()\/";.txt
var clean:String = dirty.replaceAllProhibitedCharacters();
我不是在寻找特定于操作系统的正则表达式,而是一个跨平台的解决方案。
答案 0 :(得分:7)
不允许的字符列表不会因底层操作系统而改变,它是一个固定的列表。从FileReference.download()
的文档中,不允许的字符列表是:
/\:*?"<>|%
修改:看起来也不允许@
。
如果要从任意字符串中删除这些字符,可以执行以下操作:
var validFileName:String = invalidFileName.replace(/[\/\\:*?"<>|%@]/g, "");
如果您想用其他内容替换它们,请将第二个参数更改为replace()
。
修改:添加了@
个字符;转义了/
字符。
答案 1 :(得分:3)
之前的回答对我不起作用。这就是工作(使用Flex 4.5):
public class FileNameSanitizer
{
public static function sanitize( fileName:String ):String
{
var p:RegExp = /[:\/\\\*\?"<>\|%]/g;
return fileName.replace( p, "" );
}
}
用于证明它的测试用例:
import flexunit.framework.TestCase;
public class FileNameSanitizerTest extends TestCase
{
public function FileNameSanitizerTest()
{
}
public function testSanitize():void
{
assertEquals( "bla", FileNameSanitizer.sanitize( "bla" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla/foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla\\foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla:foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla*foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla?foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla\"foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla<foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla>foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla|foo" ) );
assertEquals( "blafoo", FileNameSanitizer.sanitize( "bla%foo" ) );
assertEquals( "", FileNameSanitizer.sanitize( "/\\:*?\"<>|%" ) );
}
}