使用Twitter API无法上传图片

3

我正在使用由Net::Twitter(cpan链接)提供的Twitter API。我可以发布状态,但无法上传图片。

Perl代码:

use strict;
use warnings;
use MIME::Base64;

use Net::Twitter;
use Scalar::Util 'blessed';

# When no authentication is required:
#my $nt = Net::Twitter->new(legacy => 0);
my $consumer_key = "consumerkey";
my $consumer_secret = "consumersecret";
my $token="token";
my $token_secret="tokensecret";

# As of 13-Aug-2010, Twitter requires OAuth for authenticated requests
my $nt = Net::Twitter->new(
    traits   => [qw/API::RESTv1_1/],
    consumer_key        => $consumer_key,
    consumer_secret     => $consumer_secret,
    access_token        => $token,
    access_token_secret => $token_secret,
);
eval { 
#my $result = $nt->update({status=>'some message'}); ##this works fine
my $result = $nt->upload({media=>'/some/path/toimage.jpeg' ,media_data => encode_base64('/some/path/toimage.jpeg')}); #this line produces error
    };

if ( my $err = $@ ) {
    die $@ unless blessed $err && $err->isa('Net::Twitter::Error');

    warn "HTTP Response Code: ", $err->code, "\n",
         "HTTP Message......: ", $err->message, "\n",
         "Twitter error.....: ", $err->error, "\n";
}

错误:

HTTP Response Code: 400

HTTP Message......: Bad Request 

Twitter error.....: media type unrecognized.
2个回答

1

在从这个答案这里得到启发后,我用Perl也做了同样的事情:

my @filename = ('path/to/image.jepg');
my $result = $nt->update_with_media({status=>'hI',media=>\@filename});

这个完美地解决了问题。虽然只有数组引用在这里起作用。

注意:根据文档和@simbabque的回答link

上传 上传(media)

参数:媒体
必需:媒体
上传图片到Twitter,而不在时间轴上发布它们

返回值:图像

我猜这只会上传但不会在时间轴上显示。所以我使用update_with_media方法来发布图片。


啊,我以为你只想上传。 - simbabque
可能有点混淆,我原本以为上传会直接发布到时间线上,但看到你的回答后意识到了它的实际作用,并使用了update_with_media。无论如何,由于没有适当的文件说明,我花了2个小时来完成更新媒体的工作。 - Nagaraju
我明白了,很高兴现在它可以运行。 :) 你可以提交一个补丁给作者,并添加更多的文档。Github代码库链接在CPAN上(https://github.com/semifor/Net-Twitter)。我相信作者会感激的。 - simbabque

0

文档上传的说明有点简略,但它确实需要一个叫做media的东西。

上传

上传(media)

参数:media
必需:media
在Twitter上上传图片而不在时间轴上发布它们

返回:图像

然而,在update_with_media的正上方,它描述了一个实体media

The media[] parameter is an arrayref with the following interpretation:

[ $file ]
[ $file, $filename ]
[ $file, $filename, Content_Type => $mime_type ]
[ undef, $filename, Content_Type => $mime_type, Content => $raw_image_data ]

所以基于这个,我会期望你的上传应该长成这样:

my content_of_image_file; # open the file and read its content in binary mode
my $result = $nt->upload([
  undef,
  'filename_as_it_should_appear_on_twitter.jpeg', # this is a guess
  Content_Type => 'image/jpeg',
  Content => encode_base64($content_of_image_file),
]);

请注意,我尚未测试此代码。


你能澄清一下这里的二进制模式是什么意思吗? - Nagaraju
好的,我尝试使用binmode来打开文件,但仍然出现相同的错误。 - Nagaraju

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接