I create an android application that uploads an image from a gallery to Firebase storage, I need to use HttpPost to upload the image.
My code is as the following:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
switch (requestCode) {
case TAKE_AVATAR_GALLERY_REQUEST:
if (resultCode == Activity.RESULT_OK) {
Uri photoUri = data.getData();
Bitmap avatar= Media.getBitmap(getContentResolver(), photoUri);
String strAvatarFilename = "avatar.jpg";
try {
avatar.compress(CompressFormat.JPEG, 100,
openFileOutput(strAvatarFilename, MODE_PRIVATE));
} catch (Exception e) {
Log.e(DEBUG_TAG, "Avatar compression and save failed.", e);
}
Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(
QuizSettingsActivity.this.getFilesDir(), strAvatarFilename));
Editor editor = mGameSettings.edit();
editor.putString(GAME_PREFERENCES_AVATAR,
imageUriToSaveCameraImageTo.getPath());
editor.commit();
In the doInBackground method I call postAvatarToServer which is as following :
private boolean postAvatarToServer() {
boolean succeeded = false;
String avatar = mGameSettings.getString(GAME_PREFERENCES_AVATAR, "");
MultipartEntity entity = new
MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(avatar);
if (file.exists()) {
FileBody encFile = new FileBody(file);
entity.addPart("avatar", encFile);
HttpPost request = new
HttpPost("https://firebasestorage.googleapis.com/v0/b/HERE I
WRITE THE FOLDER URL WITHOUT [gs://]/o/");
request.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(request);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String responseString = null;
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
succeeded = true;
} catch (ClientProtocolException e) {
Log.e(DEBUG_TAG, "Unexpected ClientProtocolException",e);
} catch (IOException e) {
Log.e(DEBUG_TAG, "Unexpected IOException", e);
}
} else {
Log.d(DEBUG_TAG, "No avatar to upload");
succeeded = true;
}
return succeeded;
}
In the logcat I get !Error occurred! Http Status Code: 400
So where is the error and how to solve it ...
Why not use the existing Android SDK ?
Uri file = Uri.fromFile(new File("path/to/local/file.jpg"));
StorageReference storageRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = storageRef.putFile(file);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.