FileReference的使用对有效字符有限制Error: Error #2087: The FileReference.download() file name contains prohibited characters.
这很好,因为我想限制无论如何都来自底层文件系统
是否有一种通用的方法来修剪/替换所有被禁止的字符
为了清楚起见,我想要这样的东西:var dirty:String = "Eat this !@##$%%^&&*()/";.txt
var clean:String = dirty.replaceAllProhibitedCharacters();
我不是在寻找操作系统特定的正则表达式,而是一个跨平台的解决方案。
不允许的字符列表不会根据底层操作系统的不同而变化,它是一个固定列表。根据FileReference.download()
的文档,不允许使用的字符列表为:
/:*?"<>|%
编辑:看起来@
也是不允许的。
如果你想从任意字符串中删除这些字符,你可以这样做:
var validFileName:String = invalidFileName.replace(/[/\:*?"<>|%@]/g, "");
如果要将它们替换为其他内容,请将第二个参数更改为replace()
。
编辑:添加了@
字符;转义了/
字符。
前面的答案对我不起作用。这是起作用的(使用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( "/\:*?"<>|%" ) );
}
}