0

I'm trying to upload an image to Twitter using their API, but it always fails throwing an error saying it can't find the file even though it's definitely there since I'm using the same path to upload it fine to other networks and it displays correctly in my preview box.

com.twitter.sdk.android.core.TwitterApiException: /-1/1/content:/media/external/images/media/100883/ORIGINAL/NONE/1159437588: open failed: ENOENT (No such file or directory)
W/System.err:     at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:390)
W/System.err:     at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
W/System.err:     at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
W/System.err:     at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:818)

Some Googling showed this error was meant to have been fixed in an older version of the Twitter SDK for Android, and people have confirmed it was, but that was a while ago and I'm using the latest version 1.13.0.

The code I'm using to upload this is as follows:

//img = Uri passed from calling method
File photo = new File(img.getPath());
TypedFile typedFile = new TypedFile("application/octet-stream", photo);
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(twitSession);
MediaService  mediaService = twitterApiClient.getMediaService();
final StatusesService statusesService = twitterApiClient.getStatusesService();

mediaService.upload(typedFile, null, null, new Callback<Media>() {
    @Override
    public void success(final Result<Media> result) {
        statusesService.update(input, null, null, null, null,
        null, null, null, result.data.mediaIdString, new Callback<Tweet>() {
                    @Override
                    public void success(Result<Tweet> result) {
                        Log.d("Twitter image callback", "Successfully posted image and text to Twitter!");
                    }

                    @Override
                    public void failure(TwitterException e) {
                        if (result != null) {
                            Log.e("Twitter image callback", "Result is - " + result.toString());
                        }
                        Log.d("Twitter image callback", "Failed to post image and text to Twitter!");
                    }
                });
    }

    @Override
    public void failure(TwitterException e) {
        Log.d("Twitter image callback", "Failed to upload image to Twitter!");
        e.printStackTrace();
    }
});

Does anyone know what went wrong here and how I'm able to get this working?

PurplProto
  • 143
  • 2
  • 14
  • This look very complicated to simply upload a file. I am not sure this is using an external library (TwitterApiClient) but if not, you need to make sure that you are uploading less than 5MB per chunk. Also you need to use a MultiPart query that invokes INIT, APPEND (with binary) and END. – Linvi Apr 17 '16 at 21:34
  • If it is possible for you to use C# I would recommend the library I have written ([Tweetinvi](https://github.com/linvi/tweetinvi)) that will allow you to publish an image as easy as : `var media = Upload.UploadImage(File.ReadAllBytes("path"));` – Linvi Apr 17 '16 at 21:36

1 Answers1

0
/**
 * @return The MIME type for the given file.
 */
private String getMimeType(File file) {
    final String ext = getExtension(file.getName());
    if (!TextUtils.isEmpty(ext)) {
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
    }
    // default from https://dev.twitter.com/rest/public/uploading-media
    return "application/octet-stream";
}



/**
 * @return the extension of the given file name, excluding the dot. For example, "png", "jpg".
 */
private String getExtension(String filename) {
    if (filename == null) {
        return null;
    }
    final int i = filename.lastIndexOf(".");
    return i < 0 ? "" : filename.substring(i + 1);
}

private void socialTwitterLoginAndUploadMedia() {

    mTwitterAuthClient.authorize(this, new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            Call<User> user = TwitterCore.getInstance().getApiClient().getAccountService().verifyCredentials(false, false, false);
            user.enqueue(new Callback<User>() {
                @Override
                public void success(Result<User> userResult) {
                    tw_User_name = userResult.data.name;
                    tw_User_screen_Name = userResult.data.screenName;
                    tw_User_id = String.valueOf(userResult.data.id);
                    tw_User_profile_image = userResult.data.profileImageUrl;


                    if(imageFile != null) {
                        final TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
                        MyTwitterApiClient myTwitterApiClient = new MyTwitterApiClient(session);

                        RequestBody requestBodyprofilePic = null;
                        MultipartBody.Part body = null;
                        final String mimeType = getMimeType(imageFile);
                       requestBodyprofilePic = RequestBody.create(MediaType.parse(mimeType), imageFile);
                      // body = MultipartBody.Part.createFormData("media", imageFile.getName(), requestBodyprofilePic);

                        myTwitterApiClient.getMediaService().upload(requestBodyprofilePic, null, null).enqueue(new retrofit2.Callback<Media>() {
                            @Override
                            public void onResponse(Call<Media> call, Response<Media> response) {
                                Log.e("Upload Success Id int=", response.body().mediaId+"=");
                                Log.e("Upload Success Id=", response.body().mediaIdString);
                                Log.e("Upload Success Size=", response.body().size+"=");
                                Log.e("Upload Success ImageType=", response.body().image.imageType);

                            }

                            @Override
                            public void onFailure(Call<Media> call, Throwable t) {
                                Log.e(TAG, "Upload Tweet Error");
                            }
                        });
                    }
                }

                @Override
                public void failure(TwitterException exception) {
                    // Upon error, show a toast message indicating that authorization request failed.
                    Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void failure(TwitterException exception) {
            // Upon error, show a toast message indicating that authorization request failed.
            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });


}
Mainak Devsinha
  • 169
  • 1
  • 6