【问题标题】:Twit , media upload directly from a urlTwit ,直接从 url 上传媒体
【发布时间】:2018-07-10 12:40:22
【问题描述】:

我想从一个url下载一个img,然后直接上传到twitter,而不是先保存到文件中。

到目前为止,我已经测试了我在网上找到的所有方法,但没有运气。我总是收到“无法识别媒体类型”错误。

  http.get("http://localhost:9000/screenshot/capture/" + shot.slug,
          function(response){
    if (response.statusCode == 200) {

      response.setEncoding('binary');
      var imageFile = "";
      response.on('data', function(chunk){
        imageFile += chunk;
      });

      response.on('end', function(){
        imageFile = imageFile;
        // first we must post the media to Twitter
        T.post('media/upload', {media_data: imageFile.toString('base64')}, function (err, media, response) {
          if(err) return console.log("ERRR2: ", err);
          console.log("DATA: ", media);
          console.log("RESPONSE: ", response);
          // now we can assign alt text to the media, for use by screen readers and
          // other text-based presentations and interpreters
          var mediaIdStr = media.media_id;     
          var altText = "Alt text for the shot";
          var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } };
          console.log(meta_params);

          T.post('media/metadata/create', meta_params, function (err, data, response) {
            if (!err) {        
              // now we can reference the media and post a tweet (media will attach to the tweet)
              var params = { status: 'by @' + twitter_handle + ' at ' + "http://localhost:9000/" + shot.slug, media_ids: [mediaIdStr] };

              T.post('statuses/update', params, function (err, data, response) {
                console.log("DATA: ", data);              
              })
            }
          });
        });
      })
      //console.log(image);
    }

Twit 有效。我可以发送状态更新并一直使用 API。我也可以先将媒体文件保存到磁盘,然后用fs 读取它。但我想从 url 作为二进制文件获取它并以某种方式将其上传到 Twitter。

我怎样才能做到这一点?

【问题讨论】:

    标签: node.js twitter


    【解决方案1】:

    您将不得不使用流:https://nodejs.org/api/stream.html 或更具体地说:https://github.com/request/request#streaming

    特别是像

    request('http://google.com/doodle.png').pipe(T.postMediaChunked)
    

    不过,执行写入磁盘的中间步骤没有问题,您只需要在之后进行清理即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2018-08-07
      • 2015-04-12
      相关资源
      最近更新 更多