How To Upload File/Video To The Server Using Volley Multipart in Android


Upload Maximum Size of video to your server in android studio.


We will upload videos using multipart volley from android device.
Multipart requests are used to send heavy data data or files like audio and video
to the server. Android Volley gives you a very faster and optimized environment to
send heavy data or files to the server.
You just Create ActivityMain and design your layout like this..

MainActivity.Xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="#DD4747"
android:textStyle="bold"
android:textSize="20sp"
android:layout_gravity="center"
android:maxLines="1"
android:text="Please Upload up to 100 mb Videos Only"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:layout_gravity="center"
android:padding="10dp"
android:elevation="5dp"
android:text="Select Video To upload"
android:textStyle="bold|italic"
android:layout_marginTop="10dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:layout_margin="10dp"
>
<VideoView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:id="@+id/videoshow"/>

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_margin="5dp"
android:orientation="vertical">

<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:maxLength="10"
android:inputType="textMultiLine"
android:singleLine="false"
android:overScrollMode="always"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
android:hint="Video Title">

<com.google.android.material.textfield.TextInputEditText
android:id="@+id/videotitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:singleLine="false"
android:maxLines="1"
android:overScrollMode="always"
android:scrollbarStyle="insideInset"
android:layout_marginTop="10dp"
android:scrollbars="vertical"
android:hint="Video Description">

<com.google.android.material.textfield.TextInputEditText
android:id="@+id/videoDecription"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>

<Button
android:id="@+id/submit"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="Submit"
android:layout_marginTop="5dp"
android:textSize="20dp" />

</LinearLayout>
</ScrollView>
</LinearLayout>

MainActivity.java

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.RetryPolicy;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView tv;
private String upload_URL = "your Api url is here ";
private RequestQueue rQueue;
private ArrayList<HashMap<String, String>> arraylist;
Uri contentURI;
String url;
URL myURL;
VideoView videoshow;
MediaController mediaController;
String spath;
String usertype;
int userid;
Button submit;


private Button btn1;
private VideoView videoView;
private static final String VIDEO_DIRECTORY = "/lnitv";
private int GALLERY = 1, CAMERA = 2;
EditText title, videoDecription;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = findViewById(R.id.videotitle);
videoDecription = findViewById(R.id.videoDecription);
submit =findViewById(R.id.submit);

submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title1 = title.getText().toString();
String VideoDect = videoDecription.getText().toString();
Toast.makeText(MainActivity.this,title1,Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,VideoDect,Toast.LENGTH_LONG).show();
String displayName =
String.valueOf(Calendar.getInstance().getTimeInMillis()+".mp4");
if (title1.isEmpty()){
title.setError("Please Enter Video Title");
title.requestFocus();
}else if (VideoDect.isEmpty()){
videoDecription.setError("Please Enter Video Description");
videoDecription.requestFocus();
}else {
uploadPDF(displayName,contentURI,title1,VideoDect);
}

}
});

videoView = findViewById(R.id.videoshow);


btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPictureDialog();
}
});

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
contentURI = data.getData();
//testing
String[] mediaColumns = {MediaStore.Video.Media.SIZE};
Cursor cursor =
MainActivity.this.getContentResolver().query(contentURI,mediaColumns,null,null,null);
cursor.moveToFirst();
int sizeColInd =cursor.getColumnIndex(mediaColumns[0]);
double fileSize =cursor.getDouble(sizeColInd);
fileSize = fileSize/1024.0;
cursor.close();
Toast.makeText(MainActivity.this,"filesize"+fileSize,Toast.LENGTH_LONG).show();

Log.d("result",""+resultCode);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
Log.d("what","cancle");
return;
}
if (requestCode == GALLERY) {
Log.d("what","gale");
if (data != null) {
String selectedVideoPath = getPath(contentURI);
Log.d("path",selectedVideoPath);
saveVideoToInternalStorage(selectedVideoPath);
videoView.setVideoURI(contentURI);
videoView.requestFocus();
videoView.start();
MediaController mc= new MediaController(MainActivity.this);
videoView.setMediaController(mc);
}
} else if (requestCode == CAMERA) {
//Uri contentURI = data.getData();
String recordedVideoPath = getPath(contentURI);

Log.d("frrr",recordedVideoPath);
saveVideoToInternalStorage(recordedVideoPath);
videoView.setVideoURI(contentURI);
videoView.requestFocus();
videoView.start();
MediaController mc= new MediaController(MainActivity.this);
videoView.setMediaController(mc);
}

spath = myFile.getAbsolutePath();
Log.d("uripath", spath);

//Find Video Length

/*long lenth = spath.length();
lenth = (lenth /1024);
Toast.makeText(UploadVideo.this,"Video Size"+lenth+"KB",Toast.LENGTH_LONG).show();
Log.d("filelenth", String.valueOf(lenth));*/


}
super.onActivityResult(requestCode, resultCode, data);

}
private void uploadPDF(final String pdfname, Uri pdffile, final String Title, final String
Description){
InputStream iStream = null;
try {
iStream = getContentResolver().openInputStream(pdffile);
final byte[] inputData = getBytes(iStream);
final ProgressDialog pDialog =
ProgressDialog.show(MainActivity.this,"","Loading...",false);
VolleyMultipartRequest volleyMultipartRequest = new
VolleyMultipartRequest(Request.Method.POST, upload_URL,
new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
pDialog.dismiss();

Log.d("ressssssoo",new String(response.data));

rQueue.getCache().clear();
try {
JSONObject jsonObject = new JSONObject(new
String(response.data));
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
jsonObject.toString().replace("\\\\","");
if (jsonObject.getString("status").equals("true")) {
Log.d("come::: >>> ","yessssss");
arraylist = new ArrayList<HashMap<String, String>>();
JSONArray dataArray = jsonObject.getJSONArray("data");

for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataobj = dataArray.getJSONObject(i);
String url1 = dataobj.optString("video");
VideoModal ob = new VideoModal(MainActivity.this);

ob.setVideourl(url1);

}

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

}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();

Toast.makeText(getApplicationContext(), error.getMessage(),

Toast.LENGTH_SHORT).show();
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
// params.put("tags", "ccccc"); add string parameters

params.put("Userid", String.valueOf(userid));
params.put("Usertype",usertype);
params.put("Title",Title);
params.put("Desc",Description);
return params;
}
/*
*pass files using below method
* */
@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
params.put("filename", new DataPart(pdfname ,inputData));
return params;
}
};

volleyMultipartRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)

);
volleyMultipartRequest.setRetryPolicy(new RetryPolicy() {
@Override
public int getCurrentTimeout() {
return 50000;
}
@Override
public int getCurrentRetryCount() {
return 50000;
}
@Override
public void retry(VolleyError error) throws VolleyError {
}
});
rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(volleyMultipartRequest);

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

}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}

//testting //

private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select video from gallery",
"Record video from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
chooseVideoFromGallary();
break;
case 1:
takeVideoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void chooseVideoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takeVideoFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent, CAMERA);
}
private void saveVideoToInternalStorage (String filePath) {
File newfile;
try {
File currentFile = new File(filePath);
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() +
VIDEO_DIRECTORY);
newfile = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() +
".mp4");
if (!wallpaperDirectory.exists()) {

wallpaperDirectory.mkdirs();
}
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v("vii", "Video file saved successfully.");
}else{
Log.v("vii", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}

Note :
Now you need volleyMultipleRequestClass just copy this code to your program we
are using this class we want to send big file size data to your server in this case your server bandwidth should be high level otherwise you app will be crashed.

VolleyMultipartRequest:

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class VolleyMultipartRequest extends Request<NetworkResponse> {
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private Response.Listener<NetworkResponse> mListener;
private Response.ErrorListener mErrorListener;
private Map<String, String> mHeaders;

public VolleyMultipartRequest(int method, String url,
Response.Listener<NetworkResponse> listener,
Response.ErrorListener errorListener) {

super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
@Override
public String getBodyContentType() {
return "multipart/form-data;boundary=" + boundary;
}

@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// populate text payload
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
textParse(dos, params, getParamsEncoding());
}
// populate data byte payload
Map<String, DataPart> data = getByteData();
if (data != null && data.size() > 0) {
dataParse(dos, data);
}
// close multipart form data after text and file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Custom method handle data payload.
*
* @return Map data part label with data byte
* @throws AuthFailureError
*/
protected Map<String, DataPart> getByteData() throws AuthFailureError {
return null;
}
@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}

@Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
@Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
/**
* Parse string map into data output stream by key and value.
*
* @param dataOutputStream data output stream handle string parsing
* @param params string inputs collection
* @param encoding encode the inputs, default UTF-8
* @throws IOException
*/
private void textParse(DataOutputStream dataOutputStream, Map<String, String> params,
String encoding) throws IOException {
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());
}
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + encoding, uee);
}
}
/**
* Parse data into data output stream.
*
* @param dataOutputStream data output stream handle file attachment
* @param data loop through data
* @throws IOException
*/
private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data)
throws IOException {
for (Map.Entry<String, DataPart> entry : data.entrySet()) {
buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());
}
}
/**
* Write string data into header and data output stream.
*
* @param dataOutputStream data output stream handle string parsing

* @param parameterName name of input
* @param parameterValue value of input
* @throws IOException
*/
private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String
parameterValue) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName
+ "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(parameterValue + lineEnd);
}
/**
* Write data file into header and data output stream.
*
* @param dataOutputStream data output stream handle data parsing
* @param dataFile data byte as DataPart from collection
* @param inputName name of data input
* @throws IOException
*/
private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String
inputName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +
inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd);
if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) {
dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);
}
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new
ByteArrayInputStream(dataFile.getContent());
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

dataOutputStream.writeBytes(lineEnd);
}
class DataPart {
private String fileName;
private byte[] content;
private String type;
public DataPart() {
}
DataPart(String name, byte[] data) {
fileName = name;
content = data;
}
String getFileName() {
return fileName;
}
byte[] getContent() {
return content;
}
String getType() {
return type;
}
}
}

you need to create one modal class name is VideoModal so in
this Modal just get and set video path in your project.

VideoModal.class

import android.content.Context;
import android.content.SharedPreferences;
public class VideoModal {
Context context;
private String videourl;

SharedPreferences sharedPreferences;

public VideoModal(Context context) {

this.context = context;
sharedPreferences =
context.getSharedPreferences("video_Details",Context.MODE_PRIVATE);
}

public String getVideourl() {
videourl= sharedPreferences.getString("videourl","");
return videourl;
}
public void setVideourl(String videourl) {
this.videourl = videourl;
sharedPreferences.edit().putString("videourl",videourl).commit();
}
}

Outputof this Program :-





You just download this code from Github


Happy Coding enjoy Flutter with code with android JJ

Post a Comment

3 Comments