Android Upload Video to Remote Server Using Http Multipart Form Data

Android upload video to remote server using HTTP multipart form data

Here's the two step solution I came up with, largely from the information and links found here. This solution was easier for me to grasp than the upload2server() method in some of the related SO posts. Hope this helps someone else.

1) Select the video file from the gallery.

Create a variable private static final int SELECT_VIDEO = 3; -- it doesn't matter what number you use, so long as that's to one you check for later on. Then, use an intent to select a video.

Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select a Video "), SELECT_VIDEO);

Use onActivityResult() to start the uploadVideo() method.

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_OK) {

if (requestCode == SELECT_VIDEO) {
System.out.println("SELECT_VIDEO");
Uri selectedVideoUri = data.getData();
selectedPath = getPath(selectedVideoUri);
System.out.println("SELECT_VIDEO Path : " + selectedPath);

uploadVideo(selectedPath);
}
}
}

private String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION};
Cursor cursor = managedQuery(uri, projection, null, null, null);
cursor.moveToFirst();
String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
int fileSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
long duration = TimeUnit.MILLISECONDS.toSeconds(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)));

//some extra potentially useful data to help with filtering if necessary
System.out.println("size: " + fileSize);
System.out.println("path: " + filePath);
System.out.println("duration: " + duration);

return filePath;
}

2) Go to http://hc.apache.org/downloads.cgi, download the latest HttpClient jar, add it to your project, and upload the video using the following method:

private void uploadVideo(String videoPath) throws ParseException, IOException {

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);

FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename: " + videoPath);
StringBody description = new StringBody("This is a description of the video");

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
httppost.setEntity(reqEntity);

// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );

// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString( resEntity ) );
} // end if

if (resEntity != null) {
resEntity.consumeContent( );
} // end if

httpclient.getConnectionManager( ).shutdown( );
} // end of uploadVideo( )

Once you have it working you'll probably want to put it in a thread and add an uploading dialog, but this will get you started. Working for me after I unsuccessfully tried the upload2Server() method. This will also work for images and audio with some minor tweaking.

Add param and video(file) in multiple request by post method in Andriod

Use this
library for multipart requests, i-e image, video or any other data for POST request

Upload video from Android to server?

Had the same issue some time ago. Here's a code.

public static int upLoad2Server(String sourceFileUri) {
String upLoadServerUri = "your remote server link";
// String [] string = sourceFileUri;
String fileName = sourceFileUri;

HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";

File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();

Log.i("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)

} // end upLoad2Server

2)call it with

int reponse=upLoad2Server(""+filepath);

How to upload file to server with HTTP POST multipart/form-data?

Here's my final working code. My web service needed one file (POST parameter name was "file") & a string value (POST parameter name was "userid").

/// <summary>
/// Occurs when upload backup application bar button is clicked. Author : Farhan Ghumra
/// </summary>
private async void btnUploadBackup_Click(object sender, EventArgs e)
{
var dbFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Util.DBNAME);
var fileBytes = await GetBytesAsync(dbFile);
var Params = new Dictionary<string, string> { { "userid", "9" } };
UploadFilesToServer(new Uri(Util.UPLOAD_BACKUP), Params, Path.GetFileName(dbFile.Path), "application/octet-stream", fileBytes);
}

/// <summary>
/// Creates HTTP POST request & uploads database to server. Author : Farhan Ghumra
/// </summary>
private void UploadFilesToServer(Uri uri, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.BeginGetRequestStream((result) =>
{
try
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
using (Stream requestStream = request.EndGetRequestStream(result))
{
WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);
}
request.BeginGetResponse(a =>
{
try
{
var response = request.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var sr = new StreamReader(responseStream))
{
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string responseString = streamReader.ReadToEnd();
//responseString is depend upon your web service.
if (responseString == "Success")
{
MessageBox.Show("Backup stored successfully on server.");
}
else
{
MessageBox.Show("Error occurred while uploading backup on server.");
}
}
}
}
catch (Exception)
{

}
}, null);
}
catch (Exception)
{

}
}, httpWebRequest);
}

/// <summary>
/// Writes multi part HTTP POST request. Author : Farhan Ghumra
/// </summary>
private void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, string fileName, string fileContentType, byte[] fileData)
{
/// The first boundary
byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
/// the last boundary.
byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
/// the form data, properly formatted
string formdataTemplate = "Content-Dis-data; name=\"{0}\"\r\n\r\n{1}";
/// the form-data file upload, properly formatted
string fileheaderTemplate = "Content-Dis-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n";

/// Added to track if we need a CRLF or not.
bool bNeedsCRLF = false;

if (data != null)
{
foreach (string key in data.Keys)
{
/// if we need to drop a CRLF, do that.
if (bNeedsCRLF)
WriteToStream(s, "\r\n");

/// Write the boundary.
WriteToStream(s, boundarybytes);

/// Write the key.
WriteToStream(s, string.Format(formdataTemplate, key, data[key]));
bNeedsCRLF = true;
}
}

/// If we don't have keys, we don't need a crlf.
if (bNeedsCRLF)
WriteToStream(s, "\r\n");

WriteToStream(s, boundarybytes);
WriteToStream(s, string.Format(fileheaderTemplate, "file", fileName, fileContentType));
/// Write the file data to the stream.
WriteToStream(s, fileData);
WriteToStream(s, trailer);
}

/// <summary>
/// Writes string to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, string txt)
{
byte[] bytes = Encoding.UTF8.GetBytes(txt);
s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Writes byte array to stream. Author : Farhan Ghumra
/// </summary>
private void WriteToStream(Stream s, byte[] bytes)
{
s.Write(bytes, 0, bytes.Length);
}

/// <summary>
/// Returns byte array from StorageFile. Author : Farhan Ghumra
/// </summary>
private async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}

return fileBytes;
}

I am very much thankful to Darin Rousseau for helping me.

Uploading a File (Multipart/Form data) to Server Failed in Android using ion library

Well i have found out a simple way of uploading or posting multipart/form-data with an upload progress bar. may be this could help.

Suppose you server is waiting for the following data :

1.File(PDF,Image,Audio,Video etc.).

2.Name

3.Email

4.Address.

and you want to upload that information once in a URL be it an Absolute URL or a Relative URL, ion library is easy , precise, efficient and much better in this.

STEP 1:

declare your URI

private Uri filePath;

STEP 2:

then Pick the file from your gallery , here it's your choice you identify any kind of files you want a user to view, me here i have identified a PDF file.
on this line intent.setType("application/pdf");

private void showFileChooser() {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
}

//handling the image chooser activity result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();

Toast.makeText(getApplicationContext(), "" + filePath, Toast.LENGTH_LONG).show();
}
}

then you can call showFileChooser() in the Button for a click to access your gallery.

STEP 3:

a) Make a method Upload() containing ion library to start the job. If you see in this method , i first declared the file,name, email,address , for file it gets the URI data of a selected file or the path file , then name, email,address, it gets the data from EditText , you have to declare EditText to get the data.

b) Then identify the URL you want to use in Posting mine is url_. but make sure you include POST, in the load section .load("POST",url_).
c) Then you set the file by using .setMultipartFile("File", file) and the rest of the parameters by setting MultipartParameter .setMultipartParameter("Name", name) and so on.

public void Upload() {

String file= FilePath.getPath(this, filePath);
final String name = name_edt.getText().toString();
final String email = email_edt.getText().toString();
final String address = address_edt.getText().toString();


final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Logging in...");
pd.setCancelable(false);
pd.show();
final String url_ = "xxxxxxxxxxxxxxx";

final File file = new File(Uri.parse(path).toString());

Ion.with(MainActivity.this)
.load("POST",url_)
.progressDialog(pd)
.setMultipartFile("file", file)
.setMultipartParameter("Name", name)
.setMultipartParameter("Email", email)
.setMultipartParameter("Address.", address)

.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {

// Toast.makeText(getApplicationContext(),""+file,Toast.LENGTH_LONG).show();

System.out.println("Error " + e);
// Toast.makeText(getApplicationContext(), "Exception : " + e, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(),""+e,Toast.LENGTH_LONG).show();

pd.dismiss();

}
});
}

Then you are good to go , according to your C# API , the file will be able to save in the Folder. Even others use Php or any other language you can create your own Api to save a file in your server folder

Hope it works well.



Related Topics



Leave a reply



Submit