Search code examples
perlencodingwww-mechanize

WWW::Mechanize gives corrupted uploaded file name


I have some weird problem while uploading a file with a Cyrillic name using WWW::Mechanize. The file is uploaded correctly but the name is broken (I see only ?????? on the target site).

The code is simple:

use WWW::Mechanize;
use Encode qw(from_to);

my $config = {

    login         => "login",
    password      => "pass",
    source_folder => "$Bin/source_folder",
};

my $mech = WWW::Mechanize->new( autocheck => 1 );
$mech->agent_alias("Windows IE 6");

$mech->get("http://www.antiplagiat.ru/Cabinet/Cabinet.aspx?folderId=689935");
authorize($mech);

$mech->submit_form(

    form_number => 1,
    fields      => {},
    button =>
'ctl00$ctl00$Body$MainWorkSpacePlaceHolder$FolderControl_StdFolder_0$DocumentsGrid$btnAddItem',
);

find( \&wanted, $config->{source_folder} );

sub wanted {

    return unless -f;

    say $config->{source_folder} . "/" . $_;

    #from_to($_, "CP1251", "UTF8"); doesn't work too :-(

    my $mech = $mech->clone();
    $mech->submit_form(

        form_number => 1,
        fields      => {

            'ctl00$ctl00$Body$MainWorkSpacePlaceHolder$fuDocumentUpload' =>
              $config->{source_folder} . "/" . $_,
        },
        button => 'ctl00$ctl00$Body$MainWorkSpacePlaceHolder$btnCommitUpload',
    );
}

If I encode the file name from CP1251 to UTF8 then the upload doesn't work. Please help me to find a solution.


Solution

  • Here is solution I use:

       my $filename = $_;
        from_to( $filename, "CP1251", "UTF8" );
    
        my $mech = $mech->clone();
    
        my $form = $mech->form_number(1);
        $mech->field( 'ctl00$ctl00$Body$MainWorkSpacePlaceHolder$fuDocumentUpload',
            $config->{source_folder} . "/" . $_ );
        $form->find_input(
            'ctl00$ctl00$Body$MainWorkSpacePlaceHolder$fuDocumentUpload')->filename($filename);
        $mech->submit_form(
    
            form_number => 1,
            button => 'ctl00$ctl00$Body$MainWorkSpacePlaceHolder$btnCommitUpload',
        );