use of com.keylesspalace.tusky.network.ProgressRequestBody in project Tusky by tuskyapp.
the class ComposeActivity method uploadMedia.
private void uploadMedia(final QueuedMedia item) {
item.readyStage = QueuedMedia.ReadyStage.UPLOADING;
String mimeType = getContentResolver().getType(item.uri);
MimeTypeMap map = MimeTypeMap.getSingleton();
String fileExtension = map.getExtensionFromMimeType(mimeType);
final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name), String.valueOf(new Date().getTime()), StringUtils.randomAlphanumericString(10), fileExtension);
byte[] content = item.content;
if (content == null) {
InputStream stream;
try {
stream = getContentResolver().openInputStream(item.uri);
} catch (FileNotFoundException e) {
Log.d(TAG, Log.getStackTraceString(e));
return;
}
content = MediaUtils.inputStreamGetBytes(stream);
IOUtils.closeQuietly(stream);
if (content == null) {
return;
}
}
if (mimeType == null)
mimeType = "multipart/form-data";
item.preview.setProgress(0);
ProgressRequestBody fileBody = new ProgressRequestBody(content, MediaType.parse(mimeType), // If request body logging is enabled, pass true
false, new // may reference activity longer than I would like to
ProgressRequestBody.UploadCallback() {
int lastProgress = -1;
@Override
public void onProgressUpdate(final int percentage) {
if (percentage != lastProgress) {
runOnUiThread(() -> item.preview.setProgress(percentage));
}
lastProgress = percentage;
}
});
MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, fileBody);
item.uploadRequest = mastodonApi.uploadMedia(body);
item.uploadRequest.enqueue(new Callback<Attachment>() {
@Override
public void onResponse(@NonNull Call<Attachment> call, @NonNull retrofit2.Response<Attachment> response) {
if (response.isSuccessful()) {
onUploadSuccess(item, response.body());
} else {
Log.d(TAG, "Upload request failed. " + response.message());
onUploadFailure(item, call.isCanceled());
}
}
@Override
public void onFailure(@NonNull Call<Attachment> call, @NonNull Throwable t) {
Log.d(TAG, "Upload request failed. " + t.getMessage());
onUploadFailure(item, call.isCanceled());
}
});
}
Aggregations