How to Upload Large Video FIle on server? - android

How to Upload Large Video FIle on server?
I want up to 50 to 60mb video File on Server but I dont know how its possible. I could not Upload up to 15mb video file on server. Please have any solution Then let me know.
public static String postRequestvideo_test(String url, byte[] video,
byte[] image, List data) {
String result = "";
Log.i("video_upload", video + "");
try {
HttpPost httpPost = new HttpPost(url);
// StringEntity se;
// se = new StringEntity(data, HTTP.UTF_8);
// httpPost.setEntity(new UrlEncodedFormEntity(data));
httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("video_thumbnail", new ByteArrayBody(image,
"imagename" + ".jpeg"));
mpEntity.addPart("video",
new ByteArrayBody(video, "hyman" + ".mp4"));
mpEntity.addPart("user_key", new StringBody("user_key_test"));
mpEntity.addPart("video_name", new StringBody("video_name_test"));
mpEntity.addPart("video_duration", new StringBody(
"video_duration_test"));
mpEntity.addPart("video_thumbnail_extn", new StringBody(
"video_thumbnail_extn_test"));
httpPost.setEntity(mpEntity);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 90000000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 90000000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
result = result.trim();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
return "-333" + e.toString();
}
return result;
}

// Old Answer, please CHECK BELOW FOR NEW ANSWER
The problem you're having is probably trying to load the entire video (or for that matter any large file) in the memory at once, since the app has a maximum limited memory allowed, if you exceed that, it will cause the application to crash and give you Out of Memory exception.
What you need to do is open a connection and set it to "Keep-Alive", then open a FileInputStream for reading your video, and start reading and sending as chunks (1-4 MB is probably a good size) until all the file bytes are sent. That way you ensure the stream is sending the data while you're not exceeding your allowed memory limit for your app.
// New Answer
Please note that the above is an old answer, right now I only use MultipartEntity (org.apache.http.entity.mime.MultipartEntityBuilder) and it takes care of any file size on its own.

mpEntity.addPart(Constant.VIDEO, new FileBody(file,
"video/mp4"));
I just put it and it's done.

Related

Android Upload image and phone number to server using OkHttp

In my application I have been using DefaultHttpClient for uploading images to the server but it takes too much time to give response when server is down. I have put my code here. And AFIK DefaultHttpClient is going to be deprecated, so I want to use OkHttp instead of DefaultHttpClient. So please help me to change my code to use OkHttp for uploading images. I have searched a lot but don't know how to make the changes. please help me....
public String upLoadImg(byte[] image,String name,String phone,String imei,String randomId){
String mResponseData = null;
try{
mHttpClient = new DefaultHttpClient();
mHttpPost = new HttpPost(Constants.BASE_URL +"user/asset");
mHttpPost.setHeader("Accept", "application/json");
mHttpPost.setHeader("mobile-number", phone);
mHttpPost.setHeader("uid", imei);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if(image !=null) {
ByteArrayBody bab = new ByteArrayBody(image, name);
reqEntity.addPart("file", bab);
}
mHttpPost.setEntity(reqEntity);
Log.e("TAG", "***** mHttpClient is going to execute ");
HttpParams httpParameters = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 2 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 2 * 1000);
mHttpResponse = mHttpClient.execute(mHttpPost);
HttpEntity resEntity = null;
if(mHttpResponse!=null)
resEntity = mHttpResponse.getEntity();
if(resEntity!=null)
mResponseData = EntityUtils.toString(resEntity).trim();
}catch(HttpHostConnectException e){
Log.e("TAG","Exception cannot connect to server while sending images ",e);
return null;
}catch(Exception e){
Log.e("TAG","Exception occured while sending images ",e);
return null;
}
return mResponseData;
}
I had overcame this issue by replacing DefaultHttpClient with Okhttpclient.
As far as i know DefaultHttpClient is deprecated in latest android versions.So i had switched to OkHttpClient and then all issues fixed

Change the name of a file right before uploaded to server

I need to upload an image to my server under a specific name, but ideally, I would like to still keep image stored on the device under the original file name. This is what I tried:
myImageFile.renameTo(new File("mobileimage.jpg"));
but when the file was uploaded to the server, it did not appear to have my new name. Here is the full code that uploads the image to the server:
DefaultHttpClient mHttpClient;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
try {
myImageFile.renameTo(new File("mobileimage.jpg"));
HttpPost httppost = new HttpPost("http://mywebsite/mobile/image");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("userID", new StringBody(Constants.userID));
multipartEntity.addPart("uniqueMobileID", new StringBody(Constants.uniqueMobileID));
multipartEntity.addPart("userfile", new FileBody(myImageFile));
httppost.setEntity(multipartEntity);
HttpResponse response = mHttpClient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d(TAG, "response: " + responseBody);
return responseBody;
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
How can I change the file name?
Use the constructor of FileBody that takes the fileName as an argument
Try using the other implementation of addPart when attaching the file, so that you may add the filename field to the HTTP request. Something like this:
FormBodyPart userFile = new FormBodyPart("userfile", new FileBody(myImageFile));
userFile.addField("filename","NEWNAMEOFILE.jpg");
multipartEntity.addPart(userFile);
Is it possible renameTo() is returning false? You should check your return values, especially with renameTo().

How to send POST request in JSON using HTTPClient in Android?

I'm trying to figure out how to POST JSON from Android by using HTTPClient. I've been trying to figure this out for a while, I have found plenty of examples online, but I cannot get any of them to work. I believe this is because of my lack of JSON/networking knowledge in general. I know there are plenty of examples out there but could someone point me to an actual tutorial? I'm looking for a step by step process with code and explanation of why you do each step, or of what that step does. It doesn't need to be a complicated, simple will suffice.
Again, I know there are a ton of examples out there, I'm just really looking for an example with an explanation of what exactly is happening and why it is doing that way.
If someone knows about a good Android book on this, then please let me know.
Thanks again for the help #terrance, here is the code I described below
public void shNameVerParams() throws Exception{
String path = //removed
HashMap params = new HashMap();
params.put(new String("Name"), "Value");
params.put(new String("Name"), "Value");
try {
HttpClient.SendHttpPost(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In this answer I am using an example posted by Justin Grammens.
About JSON
JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.
The Parts
A fan object with email as a key and foo#bar.com as a value
{
fan:
{
email : 'foo#bar.com'
}
}
So the object equivalent would be fan.email; or fan['email'];. Both would have the same value
of 'foo#bar.com'.
About HttpClient Request
The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.
public static HttpResponse makeRequest(String path, Map params) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(path);
//convert parameters into JSON object
JSONObject holder = getJsonObjectFromMap(params);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
Map
If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.
private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {
//all the passed parameters from the post request
//iterator used to loop through all the parameters
//passed in the post request
Iterator iter = params.entrySet().iterator();
//Stores JSON
JSONObject holder = new JSONObject();
//using the earlier example your first entry would get email
//and the inner while would get the value which would be 'foo#bar.com'
//{ fan: { email : 'foo#bar.com' } }
//While there is another entry
while (iter.hasNext())
{
//gets an entry in the params
Map.Entry pairs = (Map.Entry)iter.next();
//creates a key for Map
String key = (String)pairs.getKey();
//Create a new map
Map m = (Map)pairs.getValue();
//object for storing Json
JSONObject data = new JSONObject();
//gets the value
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext())
{
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
//puts email and 'foo#bar.com' together in map
holder.put(key, data);
}
return holder;
}
Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.
(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)
Update
I just happend to get a comment about how to use the code and realized that there was a mistake in the return type.
The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature
to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse
the path variable is the url and I updated to fix a mistake in the code.
Here is an alternative solution to #Terrance's answer. You can easly outsource the conversion. The Gson library does wonderful work converting various data structures into JSON and the other way around.
public static void execute() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("subject", "Using the GSON library");
comment.put("message", "Using libraries is convenient.");
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Similar can be done by using Jackson instead of Gson. I also recommend taking a look at Retrofit which hides a lot of this boilerplate code for you. For more experienced developers I recommend trying out RxAndroid.
I recommend using this HttpURLConnectioninstead HttpGet. As HttpGet is already deprecated in Android API level 22.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Too much code for this task, checkout this library https://github.com/kodart/Httpzoid
Is uses GSON internally and provides API that works with objects. All JSON details are hidden.
Http http = HttpFactory.create(context);
http.get("http://example.com/users")
.handler(new ResponseHandler<User[]>() {
#Override
public void success(User[] users, HttpResponse response) {
}
}).execute();
There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.
/**
* This method is used to process GET requests to the server.
*
* #param url
* #return String
* #throws IOException
*/
public static String connect(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//instream.close();
}
}
catch (ClientProtocolException e) {
Utilities.showDLog("connect","ClientProtocolException:-"+e);
} catch (IOException e) {
Utilities.showDLog("connect","IOException:-"+e);
}
return result;
}
/**
* This method is used to send POST requests to the server.
*
* #param URL
* #param paramenter
* #return result of server response
*/
static public String postHTPPRequest(String URL, String paramenter) {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(URL);
httppost.setHeader("Content-Type", "application/json");
try {
if (paramenter != null) {
StringEntity tmp = null;
tmp = new StringEntity(paramenter, "UTF-8");
httppost.setEntity(tmp);
}
HttpResponse httpResponse = null;
httpResponse = httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream input = null;
input = entity.getContent();
String res = convertStreamToString(input);
return res;
}
}
catch (Exception e) {
System.out.print(e.toString());
}
return null;
}

Set image type in android

I have some code to post an image to my php script that uploads to a database, when it adds to the database the file type is application/oct???? (what is this)
is there anyway of changing this to a jpg file at the android stage?
Below is my code
HttpClient client = new DefaultHttpClient();
String postURL = "http://10.0.2.2:90/mobileupload3.php";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("image", bin);
reqEntity.addPart("name", new StringBody(enteredName));
reqEntity.addPart("gender", new StringBody(radio));
reqEntity.addPart("cat", new StringBody(radio2));
reqEntity.addPart("lat", new StringBody(lat));
reqEntity.addPart("lon", new StringBody(lon));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
application/oct (I assume you mean application/octet-stream) is a MIME type for a general binary file.
Without more information on your method of upload, I believe that the other part of your question has already been answered on SO here.

Android - image upload sending no content

I've been looking into this for the last day or two and can not seem to find a solution to my issue. I am trying to post an image to a server using httppost.
I have tried two ways of doing this and both complete the post but with no content i.e. the content length is 0.
The first is as follows:
String url = "MYURL";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/DCIM/100MSDCF/DSC00004.jpg");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here","--------Error--------Response Status line code:"+response.getStatusLine());
}else {
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
and the second is:
String url = "MYURL";
//File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(Environment.getExternalStorageDirectory(),"/DCIM/100MSDCF/DSC00004.jpg");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("finishing", "The try catch function");
} catch (Exception e) {
// show error
}*/
As you can see I have hardcoded a path to a specific image, this is to be dynamic when I get it up and running.
Can anyone see what i'm doing wrong? Am I leaving out something? I know I use setChunked and setContenttype - is there a setContent option?
Any help would be grately appreciated.
Thanks,
jr83.
You can use upload your image by sending multipart messages; you might find this discussion useful.

Categories

Resources