How to upload videos using multi part post entity? - android

I use this code that i found in some page but I only can upload images from my android application to the server and is working, but when i upload a video(.mp4) its saved as "file" like unknown.
public void upload() throws Exception {
//Url of the server
String url = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity mpEntity = new MultipartEntity();
//Path of the file to be uploaded
String filepath = "";
File file = new File(filepath);
ContentBody cbFile = new FileBody(file);
//Add the data to the multipart entity
mpEntity.addPart("image", cbFile);
mpEntity.addPart("name", new StringBody("Test", Charset.forName("UTF-8")));
mpEntity.addPart("data", new StringBody("This is test report", Charset.forName("UTF-8")));
post.setEntity(mpEntity);
//Execute the post request
HttpResponse response1 = client.execute(post);
//Get the response from the server
HttpEntity resEntity = response1.getEntity();
String Response=EntityUtils.toString(resEntity);
Log.d("Response:", Response);
//Generate the array from the response
JSONArray jsonarray = new JSONArray("["+Response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
//Get the result variables from response
String result = (jsonobject.getString("result"));
String msg = (jsonobject.getString("msg"));
//Close the connection
client.getConnectionManager().shutdown();
}
There is any way to make this work to upload videos too?

There is not issue with this code works fine for upload videos and images, the problem was i´m missing the file extension in the name, so when the video was uploaded it should be NAME.EXTENSION not only NAME.
NOTE:
For all the people who is trying to upload a large(2MB-10GB) image or video to the server the only solution i found was encode the file in chunks and upload each chunk to the server, from there you only have to encode the chunks again. NO SIZE LIMITATION :)!!!!

Related

Upload image to the server using multipartentity and json in android

I have read lots of post to achieve the task like to upload image along with parameters using multipartentity and josn in android, but my problem is when i was trying to upload image and parameter without converting string to JSONobject then image has uploaded without an error but when i was trying to add response string to jsonobject then error occur in the logcat like ):
error: Value`<form of type java.lang.String cannot be converted to JSONObject.
Any one please help to resolve this issue? I want to send an image and JsonObject to an PHP Server with MultipartEntity. I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app.
Here is my Code:
public JSONObject doFileUpload(String _fname, String _lname, String _email,
String _password, String _country, String _countrycode,
String _phone) {
File file1 = new File(selectedPath);
String urlString = "http://capstonehostingservices.com/fetch_new/app/index.php/fetch/register";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("photo", bin1);
reqEntity.addPart("first_name", new StringBody(_fname));
reqEntity.addPart("last_name", new StringBody(_lname));
reqEntity.addPart("email", new StringBody(_email));
reqEntity.addPart("password", new StringBody(_password));
reqEntity.addPart("country", new StringBody(_country));
reqEntity.addPart("country_code", new StringBody(_countrycode));
reqEntity.addPart("phone", new StringBody(_phone));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
String response_str = EntityUtils.toString(resEntity);
json = new JSONObject(response_str);
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return json;
}
In above code i was trying to convert response string to jsonobject, how to i achieve this?
I used selectedpath parameter as to get image path from gallary, I want to send an image and a JsonObject to an PHP Server with MultipartEntity. I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app.
This may not be the best answer but it is a very good example to get started.
Use the following function to send file to server:
public static void postFile(String fileName) throws Exception {//fileName is path+filename of picture
String url_upload_image = "http://url-to-api/upload_photo.php";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_upload_image);
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder
.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", new FileBody(new File(fileName)));
post.addHeader("id", id);//id is anything as you may need
post.setEntity(multipartEntity.build());
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
entity.consumeContent();
client.getConnectionManager().shutdown();
}
PHP file that is at http://url-to-api/upload_photo.php
<?php
$name = $_POST['id'];
$file_path = "images/";
$file_path = $file_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
echo "success";
echo $name;
} else{
echo "fail";
}
?>
And make sure that your directory or folder in server is Executable, Writable and Readable. I had this as the major problem. This is called 777 permission.. Believe me, this is as important as other things to consider.

Send Image and String by using MultipartEntity

I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app. My upload code is like below:
public String uploadFile() throws Exception
{
String result = "";
try
{
HttpResponse response = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(_url);
request.setHeader("Accept", "application/json");
File file=new File(filePath);
String fileName=file.getName();
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
imageEntity.addPart("imageName", new StringBody(fileName));
imageEntity.addPart("image", new FileBody(file, "application/octet-stream"));
request.setEntity(imageEntity);
response = httpClient.execute(request);
InputStream dataStream = response.getEntity().getContent();
BufferedReader dataReader = new BufferedReader(new InputStreamReader(dataStream));
String line = "";
while ((line = dataReader.readLine()) != null)
result+=line;
}
catch (Exception e)
{
}
return result;
}
I get response from my server but in my web service code Request.Files has no file. If I change the line:
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
to
MultipartEntity imageEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
app is in process for a long time (about 3-4 minutes) and throws error. This is caused if I add an image. If I send only StringBody without FileBody, I get response from server and Request.Files in my webservice code return file count correctly. How can I fix this problem and upload image correctly? Any suggestion?

Uploading file via form into GAE from Android

I have an app on GAE at: http://1.myawesomecity.appspot.com/
FIXED:
HttpPost post = new HttpPost("http://1.myawesomecity.appspot.com/");
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
String actualURL = result.substring(result.indexOf("http://"), result.indexOf("\" method"));
Log.w("asdf", "url " + actualURL );
post = new HttpPost(actualURL);
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
String mime_type = "image/png";
File file = new File( filename ); //context.getFilesDir(),
entity.addPart( "myFile", new FileBody( file, mime_type));
post.setEntity( entity );
String res = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
Log.w("asdf", res);
The above grabs the ACTUAL upload URL from the GAE server, and passes in the file as dictated by the CORRECT answer below.
Old Question:
As you can see, if you choose a file and hit submit, it will 404, but the file actually does get stored (as long as it is not too big, < 100kb). Don't type in anything in the first text field.
Now, putting aside how this particular app is barely functional, I'm trying to upload a file from Android onto this server.
The site's upload script uses blobstore, and the file field's name is "myFile".
Now in my Android app, I have:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<my app's url>);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myFile", <path to a file selected by user> ) );
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
This throws an exception.
How is this any different from me going to my site through a browser, choosing a file, and hitting submit? Why does going through a browser actually go through with uploading the file, when the Android code does not?
I know that my filepath is valid. Is there something I'm doing wrong? or is clicking on "submit" from a browser different from executing a httpclient from Android?
Uploading file to a blobstore on GAE is a two step process:
first you need to get a proper URL where to POST your data, usually people use something like "/bloburl" handler for that purpose
when you have blob upload URL, you use it in your request.
the file you send does not go as NameValuePair, it's supposed to go as a MultiPartEntity.
here's the code that works (you'll need apache http library for MultiPartEntry support):
DefaultHttpClient http_client = new DefaultHttpClient();
HttpGet http_get = new HttpGet(Config.BASE_URL + "bloburl");
HttpResponse response = http_client.execute(http_get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String first_line = reader.readLine();
Log.w(TAG, "blob_url: " + first_line);
HttpPost post = new HttpPost(first_line);
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
mime_type = "application/zip";
File file = new File( context.getFilesDir(), filename );
entity.addPart( "file", new FileBody( file, mime_type));
post.setEntity( entity );
String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
Log.i(TAG, result);

Trouble Uploading Image from Android to Rails Server Using PaperClip

I'm trying to upload images to my rails server from Android. All my other data uploads, but I get a "Error invalid body size" error. It has to do with the image. Below is my code. Help?!
public void post(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("content_type","image/jpeg");
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("picture_file_name", new StringBody("damage.jpg"));
File file = new File((imageUri.toString()));
entity.addPart("picture", new FileBody(file, "image/jpeg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
I've tried removing the browser compatible parameter, but it doesn't help. my image is being stored as an URI called imageUri. I'm using paperclip gem.
thanks!
This is how I solved.
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (NameValuePair nameValuePair : nameValuePairs) {
if (nameValuePair.getName().equalsIgnoreCase("picture")) {
File imgFile = new File(nameValuePair.getValue());
FileBody fileBody = new FileBody(imgFile, "image/jpeg");
multipartEntity.addPart("post[picture]", fileBody);
} else {
multipartEntity.addPart("post[" + nameValuePair.getName() + "]", new StringBody(nameValuePair.getValue()));
}
}
httpPost.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(httpPost, httpContext);
This will produce a POST like this:
{"post"=>{"description"=>"fhgg", "picture"=>#<ActionDispatch::Http::UploadedFile:0x00000004a6de08 #original_filename="IMG_20121211_174721.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"IMG_20121211_174721.jpg\"\r\nContent-Type: image/jpeg\r\nContent-Transfer-Encoding: binary\r\n", #tempfile=#<File:/tmp/RackMultipart20121211-7101-3vq9wh>>}}
In the rails application your model attributes must have the same name you use in your request
, so in my case
class Post < ActiveRecord::Base
attr_accessible :description, :user_id, :picture
has_attached_file :picture # Paperclip stuff
...
end
I have also disabled the CSRF token from the rails application.

Upload image from android to python appengine blobstore

I have struggled for quite some time to upload photo images from android to python appengine
This is what I have tried, in Android:
void apachePost() throws Exception {
File image = new File("/sdcard/image.jpg");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://clockinapple.appspot.com/upload");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(image));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.v(Constants.DATA, "received http response " + response);
} catch (ClientProtocolException e){
}
}
In appengine:
class UserPhoto(db.Model):
user = db.StringProperty()
blob_key = blobstore.BlobReferenceProperty()
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload = self.get_uploads()[0]
user_photo = UserPhoto(user="test", blob_key=upload.key())
db.put(user_photo)
return user_photo.key()
My logged server error is "Apache-HttpClient/UNAVAILABLE (java 1.4)"
I assume the headers are incorrect - I have tried many variations
Some of the links are have tried:
Ika Lan's snippet
tacticalnuclearstrike blog
I would really appreciate any help, I don't seem to be asking the right questions atm
This is what I have that works (Changed to a HttpGet), the Android code:
void apachePost(String url, String filename) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse urlResponse = httpClient.execute(httpGet);
String result = EntityUtils.toString(urlResponse.getEntity());
Uri fileUri = Uri.parse(filename); // Gets the Uri of the file in the sdcard
File file = new File(new URI(fileUri.toString())); // Extracts the file from the Uri
FileBody fileBody = new FileBody(file, "multipart/form-data");
StringBody stringBody = new StringBody("Arghhh");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", fileBody);
entity.addPart("string", stringBody);
HttpPost httpPost = new HttpPost(result);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
response.getStatusLine();
Log.v(Constants.DATA, "received http response " + response);
Log.v(Constants.DATA, "received http entity " + entity);
}
The Appengine Code:
class GetBlobstoreUrl(BaseHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload/')
logging.debug(upload_url)
self.response.out.write(upload_url)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
text_files = self.get_uploads('string')
blob_info = upload_files[0]
user_info = "text_files"
photo = clockin.UserPhoto(blob_key=blob_info.key(), user=user_info)
photo.put()
One thing that eludes me is what happened to the "entity.addPart("string", stringBody);"
it doesnt seem part of get_uploads in the blobstore object

Categories

Resources