سؤال

The use of FileReference has a constraint on valid characters.
Error: Error #2087: The FileReference.download() file name contains prohibited characters.
This is fine since I guess the restriction comes from the underlying file system anyway

Is there such a things as a generic way to trim / replace all prohibited characters?

For clarity I am after something like:
var dirty:String = "Eat this !@##$%%^&&*()\/";.txt
var clean:String = dirty.replaceAllProhibitedCharacters();

I am not looking for OS specific regular expressions, but a cross platform solution.

هل كانت مفيدة؟

المحلول

The list of disallowed characters does not change depending on the underlying OS, it is a fixed list. From the documentation for FileReference.download() the list of disallowed characters is:

/\:*?"<>|%

Edit: It looks like @ isn't allowed either.

If you want to remove those characters from an arbitrary string you can do something like this:

var validFileName:String = invalidFileName.replace(/[\/\\:*?"<>|%@]/g, "");

If you want to replace them with something else, then change the second parameter to replace().

Edit: added the @ character; escaped the / character.

نصائح أخرى

The previous answer did not work for me. This is what did work (Using Flex 4.5):

public class FileNameSanitizer
{
public static function sanitize( fileName:String ):String
{
    var p:RegExp = /[:\/\\\*\?"<>\|%]/g;
    return fileName.replace( p, "" );
}
}

And the testcase to prove it:

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( "/\\:*?\"<>|%" ) );
    }

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top