How to Upload File Using Volley Library in Android

Uploading image to server using volley with multi-part data in body of post request

I was able to achieve this using retrofit 2, here's the code.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {

//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

//displaying selected image to imageview
logo.setImageBitmap(bitmap);

//calling the method uploadBitmap to upload image
loading.setVisibility(View.VISIBLE);
///uploadBitmap(bitmap);

File file = new File(getRealPathFromUri(this, imageUri));
uploadImageFile(file);

} catch (IOException e) {
e.printStackTrace();
}
}
}

public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

private void uploadImageFile(File file) throws IOException {

file = new Compressor(this).compressToFile(file);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
// MultipartBody.Part is used to send also the actual filename
MultipartBody.Part body = MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);

ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.uploadFile("Bearer "+jsonToken, body);
call.enqueue(new Callback< ServerResponse >() {
@Override
public void onResponse(@NonNull Call < ServerResponse > call, @NonNull retrofit2.Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();

if (serverResponse.getData() != null) {
Log.e(TAG, "Response is "+ serverResponse.getData());
loading.setVisibility(View.GONE);
Toast.makeText(ProfileSettings.this, "Avatar updated", Toast.LENGTH_SHORT).show();
} else {
Log.e("Response", String.valueOf(serverResponse));
}
}

@Override
public void onFailure(Call < ServerResponse > call, Throwable t) {
Log.e(TAG, t.getMessage());
}
});
// Log.e(TAG, "request is "+call.request().body()+" and "+call.request().headers());
}

How to upload video in android using volley

Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);

and after selecting video

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri aa = data.getData();
mVideoURI = Uri.parse(String.valueOf(aa));
}
}

dont forget to use private Uri mVideoURI;
at top

inside your post volley method use :

@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
/// photo field in link
if (mVideoURI != null) {
params.put("video", new DataPart("file_avatar.mp4", UploadHelper.getFileDataFromDrawable(getActivity(), mVideoURI)));
}
return params;
}

UPDATE

1- CREATE BroadcastHelper CLASS :

public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.scott";
private static final String UPDATE_LOCATION_METHOD = "update";

public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}

}

2- Send intent from your adapter

holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});

3- in your fragment this use :

Receiver receiver;
boolean isReciverRegistered = false;

@Override
public void onResume() {
super.onResume();

if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}

@Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}

private class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {

case "url":

/* call post method here */

default:
break;
}
}
}
}

UploadHelper Class :

    public class UploadHelper {

/**
* Turn drawable resource into byte array.
*
* @param context parent context
* @param id drawable resource id
* @return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}

/**
* Turn drawable into byte array.
*
* @return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, Uri uri) {
// Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
InputStream iStream = context.getContentResolver().openInputStream(uri);
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];

// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
if (iStream != null) {
while ((len = iStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}

}

Upload an image using Google Volley

I have an example to upload images by Google Volley. Take a look:

package net.colaborativa.exampleapp.api;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

public class PhotoMultipartRequest<T> extends Request<T> {

private static final String FILE_PART_NAME = "file";

private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File mImageFile;
protected Map<String, String> headers;

public PhotoMultipartRequest(String url, ErrorListener errorListener, Listener<T> listener, File imageFile){
super(Method.POST, url, errorListener);

mListener = listener;
mImageFile = imageFile;

buildMultipartEntity();
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();

if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}

headers.put("Accept", "application/json");

return headers;
}

private void buildMultipartEntity(){
mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}

@Override
public String getBodyContentType(){
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}

@Override
public byte[] getBody() throws AuthFailureError{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}

return bos.toByteArray();
}

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}

@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}

And you can use it like this:

RequestQueue mQueue = Volley.newRequestQueue(context);
PhotoMultipartRequest imageUploadReq = new PhotoMultipartRequest(url, ErrorListener, Listener, imageFile);
mQueue.add(imageUploadReq);

I hope these codes will inspire you.

How is it possible to upload large files with Volley? ( Android )

Read this: Volley Issue

From the link: "It[volley] inherently requires that the full request/response be storable in memory, and for video uploads it makes far more sense to stream them incrementally over the network from another source (i.e. disk), to support resume of partial uploads, etc, in a way that Volley's API inherently doesn't support."

How to upload Image on server using Volley?

You should have to understand the concept to use of volley library and image uploads. Here are some other useful links for image upload and use of volley library.

volley library

Image upload using multipart

Note: I have also tested your tutorial.code are ok. Please check your image path properly. If possible then use their php code on any hosted web server. and check their json response and cross check your parameter which you have passed with server script's parameters..



Related Topics



Leave a reply



Submit