How to post image on twitter in Phonegap using javascript

后端 未结 2 1271
鱼传尺愫
鱼传尺愫 2021-02-05 15:59

I\'m currently implementing a web smartphone application with Phonegap. On this application, users can post images they take with the phone camera on Facebook. This feature has

2条回答
  •  攒了一身酷
    2021-02-05 16:14

    According to the docs, Twitter requires the multipart/form-data enctype, which means a base64 string isn't going to work.

    Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter ~ https://dev.twitter.com/docs/api/1/post/statuses/update_with_media

    However, you could host an endpoint that takes base64, converts it to a real file, and forwards the request to Twitter. For example (untested):

     $_POST['consumer_key'],
        'consumer_secret' => $_POST['consumer_secret'],
        'user_token'      => $_POST['user_token'],
        'user_secret'     => $_POST['user_secret'],
    ));
    
    // note the type and filename are set here as well
    // Edit: Not sure if the `type` and `filename` params are necessary.
    $params = array( 'media[]' => "@{$temp_file};type={$temp_type};filename={$temp_name}" );
    
    $code = $tmhOAuth->request( 'POST', $tmhOAuth->url( '1/status/update_with_media' ),
        $params,
        true, // use auth
        true  // multipart
    );
    
    // Remove temp file.
    unlink( $temp_file );
    
    if ( $code == 200 ) {
        tmhUtilities::pr( json_decode( $tmhOAuth->response['response'] ) );
    }
    tmhUtilities::pr( htmlentities( $tmhOAuth->response['response'] ) );
    
    ?>
    

    And you might call it like:

        $.ajax({
            // You'll want to use https to protect the oauth info.
            url: "https://mysite.com/proxy.php",
            type: "POST",
            data: {
                image: "base64 data...",
                name: "foo.png",
                consumer_key: options.consumerKey,
                consumer_secret: options.consumerSecret,
                user_token: options.accessTokenKey,
                user_secret: options.accessTokenSecret
            },
            success: function( data ) {
                console.log( data );
            }
        });
    

提交回复
热议问题