Upload a file from Android to the server via PHP - php

Can anyone help me to make my code work, i.e. upload a file from Android to the server via PHP? I tried it in many different ways but it won't work. I get HTTP Response 200 but the files aren't uploaded on server.
The PHP script I'm using for upload is:
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
?>
I also tried using multipart from Httpmime 4.0 but it wont work.
public void uploadFile(String path)
{
File file = new File(path);
try {
HttpClient client = new DefaultHttpClient();
String postURL = upLoadServerUri;
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded_file", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE Wahaj: ","Code : "+ EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}

public class Helpher extends AsyncTask<String, Void, String> {
Context context;
JSONObject json;
ProgressDialog dialog;
int serverResponseCode = 0;
DataOutputStream dos = null;
FileInputStream fis = null;
BufferedReader br = null;
public Helpher(Context context) {
this.context = context;
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
}
#Override
protected String doInBackground(String... arg0) {
try {
File f = new File(arg0[0]);
URL url = new URL("http://localhost:8888/imageupload.php");
int bytesRead;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
+ f.getName() + "\"";
String contentType = "Content-Type: application/octet-stream";
dos = new DataOutputStream(conn.getOutputStream());
fis = new FileInputStream(f);
dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
dos.writeBytes(contentDisposition + NEW_LINE);
dos.writeBytes(contentType + NEW_LINE);
dos.writeBytes(NEW_LINE);
byte[] buffer = new byte[MAX_BUFFER_SIZE];
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
dos.writeBytes(NEW_LINE);
dos.writeBytes(SPACER + BOUNDARY + SPACER);
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
Log.w(TAG,
responseCode + " Error: " + conn.getResponseMessage());
return null;
}
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.d(TAG, "Sucessfully uploaded " + f.getName());
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
dos.close();
if (fis != null)
fis.close();
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return String.valueOf(serverResponseCode);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
This is the AsyncTask "Helpher" class used for upload image from Android. To call this class use like syntax below.
new Main2Activity.Helpher(this).execute(fileUri.getPath());
Here fileUri.getPath() local image location.

Related

How to upload an image from android to php using asynctask

everyone. I am stuck on this project I am working on. I want to be able to upload an image from the android gallery, encode that image to a base64 string and send to PHP web service, as a get variable, then decode the image from the other end and do with it as I wish.
So far I am able to select the image, from the gallery and even encode to base64 string and storing in android preference.
The problem is, I think that not all the string is being sent to the PHP service (Some is truncated).
Why do I think so? My Log.d showed me different strings when dumped at different locations.
The code that gets the image and encodes is:-
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Please select a file"),1);
}
private String onSelectFromGalleryResult (Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver() , data.getData()) ;
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;
byte[] imageBytes = byteArrayOutputStream.toByteArray() ;
Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ;
return Base64.encodeToString (imageBytes, Base64.DEFAULT) ;
} else {
return null ;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit() ;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
/*Here we handle the image gotten from the gallery*/
String encodedGalleryImage = onSelectFromGalleryResult(data);
editor.putString("userEncodedGalleryImage" , encodedGalleryImage);
} else if (requestCode == 0) {
/*Here we handle the image that was take using the camera*/
}
editor.apply();
}
}
Here we call the asynctask class
private void callAsynctask () {
SharedPreferences sp = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
String userQuestionAttachement = sp.getString("userEncodedGalleryImage" , "") ;
Log.d("callingEncodedImage" , userQuestionAttachement) ;
}
The problem I have is that the log from Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ; is different from Log.d("callingEncodedImage" , userQuestionAttachement) ;
There both have same beginning, but different endings. I expect to see the same characters.
Can someone please help me sort it out?
In Android,
new UploadFileAsync().execute("");
private class UploadFileAsync extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String sourceFileUri = "/mnt/sdcard/abc.png";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (sourceFile.isFile()) {
try {
String upLoadServerUri = "http://website.com/abc.php?";
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
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("bill", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
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();
if (serverResponseCode == 200) {
// messageText.setText(msg);
//Toast.makeText(ctx, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
// recursiveDelete(mDirectory1);
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
// dialog.dismiss();
e.printStackTrace();
}
// dialog.dismiss();
} // End else block
} catch (Exception ex) {
// dialog.dismiss();
ex.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
In Php,
<?php
if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
$uploads_dir = './';
$tmp_name = $_FILES['bill']['tmp_name'];
$pic_name = $_FILES['bill']['name'];
move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
}
else{
echo "File not uploaded successfully.";
}
?>
To upload image using Multipart follow the following steps:
Download httpmime.jar file and add it in your libs folder.
Download http client.jar file and add it in your libs folder.
Call the following method either from a background thread or an AsyncTask.
public void executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"YOUR SERVER URL");
ByteArrayBody bab = new ByteArrayBody(data, "YOUR IMAGE.JPG");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("IMAGE", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}

Issue with uploading image from Android to Mysql

I'm working on a social app and I want to upload an image in the database, I tried a code and it worked. The file is in my folder but the problem is that the path couldn't get to the Mysql database I figured out that $_FILES['uploaded_file']['name'] is empty but I don't know how to solve this.
AddStatus.java :
public class AddStatus extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog pDialog;
EditText status;
Button send,upload_img;
String user_id;
private TextView messageText;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String imagepath=null;
JSONParser jsonParser = new JSONParser();
private static final String upLoadServerUri = "http://192.168.1.10/social/addstatus.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_status);
ImageView img= new ImageView(this);
status =(EditText)findViewById(R.id.edt_status);
send = (Button)findViewById(R.id.btn_send);
upload_img = (Button) findViewById(R.id.btn_img);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
send.setOnClickListener(this);
upload_img.setOnClickListener(this);
final Intent callingIntent = getIntent();
user_id = callingIntent.getStringExtra("user_id");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
dialog = ProgressDialog.show(AddStatus.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
String stat = status.getText().toString();
Long ts = System.currentTimeMillis();
String time = ts.toString();
new addStatus().execute(stat,user_id,time);
break;
case R.id.btn_img:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
break;
default:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap= BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
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);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
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("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(AddStatus.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(AddStatus.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(AddStatus.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
public void onPause() {
super.onPause();
if (pDialog != null)
pDialog.dismiss();
}
class addStatus extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddStatus.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String status = args[0];
String user_id = args[1];
String time = args[2];
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("status", status));
params.add(new BasicNameValuePair("user_id", user_id));
params.add(new BasicNameValuePair("time", time));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
upLoadServerUri, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(AddStatus.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
addStatus.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$response = array();
$target_path = "";
$file_upload_url = 'http://' . '192.168.1.10' . '/' . 'social' . '/' . $target_path;
if (isset($_FILES['uploaded_file']['name'])) {
$target_path = $target_path . basename($_FILES['uploaded_file']['name']);
$response['file_name'] = basename($_FILES['uploaded_file']['name']);
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['uploaded_file']['name']);
$path = $file_upload_url . basename($_FILES['uploaded_file']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}
if (isset($_POST['user_id']) && isset($_POST['status']) && isset($_POST['time'])){
$status = $_POST['status'];
$user_id = $_POST['user_id'];
$time = $_POST['time'];
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("INSERT INTO posts(user_id,text,time,image) VALUES('$user_id','$status','$time','$path')");
if ($result) {
$response["success"] = 1;
$response["message"] = "User created";
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "Registration failed";
echo json_encode($response);
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I hope you can help me with this issue. Thanks.

gzip compression in android app as client and php server

In my android app i want to send compressed data to php server using gzip compression and receive response from the server and decompress the response if it is compressed. But when i am sending compressed data,server is getting null and not the data which i am sending and it is returning error message.
This is code i am using for compression--
public static String compress(String strData) throws Exception
{
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(strData.getBytes("UTF-8"));
gzip.close();
String outStr = obj.toString("UTF-8");
return outStr;
}
This is the code used for decomprssion---
public static String decompress(String str) throws Exception
{
byte[] bytes1 = str.getBytes("UTF-8");
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes1));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
outStr += line;
}
return outStr;
}
And I also add a header to httppost request
httpPost.addHeader("Accept-Encoding", "gzip, deflate");
can anyone please tell me what to do if I want to compress data before sending to server and also receive response and decompress it, if it is compressed.
public static void main() {
String myString = "H4sIAAAAAAAAA5WMuwrCMBSGX0XOnCFpLoZ0ExH0FaTDyU0DTVsSB6H03Y3dHN3+67fCgm8wjAA6dz2DASmjUsjRCs8tahu5FCw6DQQmzKEt";
byte[] decode = Base64.decode(myString, Base64.NO_WRAP);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decode);
int read;
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(gzipInputStream));
System.out.println("read222 :" + br.readLine());
DataInputStream dataInputStream = new DataInputStream(gzipInputStream);
//System.out.println("read222 :" + dataInputStream.retoString());
for (int i = 0; i < decode.length; i++) {
read = dataInputStream.readInt();
int rRead = Integer.reverseBytes(read);
System.out.println("read :" + dataInputStream.read());
}
} catch (IOException e) {
e.printStackTrace();
}
}
run your code in a thread or asynctask or service whereever you want
Thread thread=new Thread(new Runnable()
{
#Override
public void run()
{
try
{
String body = "Naval is working on zip and unzip processed return json";
URL url = new URL("http://yourServerUrl/yourgzip.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-encoding", "gzip");
conn.setRequestProperty("Content-type", "application/octet-stream");
GZIPOutputStream dos = new GZIPOutputStream(conn.getOutputStream());
dos.write(body.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder builder=new StringBuilder();
String decodedString = "";
while ((decodedString = in.readLine()) != null)
{
builder.append(decodedString);
}
in.close();
Log.e("Data", builder.toString());
}
catch (Exception e)
{
Log.e("Datae", builder.toString());
}
}
});
thread.start();
on server side ask them to use this code
$postdata=gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) );
as $HTTP_RAW_POST_DATA deprecated so use file_get_contents() like to return array
$post = array_map('urldecode',explode('&',file_get_contents("php://input")));
or like this method to decompress a gzip stream that was pushed to my webserver
$x = file_get_contents("compress.zlib://php://input");
and using
$data_as_associate_Array=json_decode($x,true);

Upload Large Video files to the server from android

I know how to upload the file from android and I am able to do it by using the following code
private void doFileUpload(MessageModel model) {
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;// 1 MB
String responseFromServer = "";
String imageName = null;
try {
// ------------------ CLIENT REQUEST
File file = new File(model.getMessage());
FileInputStream fileInputStream = new FileInputStream(file);
AppLog.Log(TAG, "File Name :: " + file.getName());
String[] temp = file.getName().split("\\.");
AppLog.Log(TAG, "temp array ::" + temp);
String extension = temp[temp.length - 1];
imageName = model.getUserID() + "_" + System.currentTimeMillis()
+ "." + extension;
// open a URL connection to the Servlet
URL url = new URL(Urls.UPLOAD_VIDEO);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ imageName + "\"" + lineEnd);
Log.i(TAG, "Uploading starts");
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
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) {
// Log.i(TAG, "Uploading");
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
AppLog.Log(TAG, "Uploading Vedio :: " + imageName);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
Log.i(TAG, "Uploading ends");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE ----------------
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
try {
final JSONObject jsonObject = new JSONObject(str);
if (jsonObject.getBoolean("success")) {
handler.post(new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
handler.post(new Runnable() {
#Override
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
model.setMessage(imageName);
onUploadComplete(model);
inStream.close();
} catch (IOException ioex) {
ioex.printStackTrace();
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
manageQueue();
}
the code is working perfectly for short videos but it is not uploading the large files and I no hint why .:(
I know its a bad practice to just ask that why my code is not working but here I am asking why is the code behaving different for large files.
I also check other answers on StackOverFlow but didn't find any flaw in my code.
Thanks
You can try HttpClient jar 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 video of the agent");
StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
reqEntity.addPart("code", code);
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( )
Try Android Asynchronous Http Client library.
AsyncHttpClient client = new AsyncHttpClient();
File myFile = new File("/path/to/video");
RequestParams params = new RequestParams();
try {
params.put("video", myFile);
} catch(FileNotFoundException e) {}
client.post("POST URL",params, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
Try volley, add library in your project and enjoy, its fast and easy to integrate.
final AbstractUploadServiceReceiver uploadReceiver = new AbstractUploadServiceReceiver() {
#Override
public void onProgress(String uploadId, int progress) {
Log.i("", "upload with ID " + uploadId + " is: " + progress);
}
#Override
public void onError(String uploadId, Exception exception) {
String message = "Error in upload with ID: " + uploadId + ". " + exception.getLocalizedMessage();
Log.e("", message, exception);
}
#Override
public void onCompleted(String uploadId, int serverResponseCode, String serverResponseMessage) {
String message = "Upload with ID " + uploadId + " is completed: " + serverResponseCode + ", "
+ serverResponseMessage;
Log.i("", message);
}
};
uploadReceiver.register(context);
final docUploadParams item="yourdocUploadParam";
sendUploaderRequest(context, URLtoUpload, item);
public void sendUploaderRequest(Context context,String url,docUploadParams item)
{
final UploadRequest request = new UploadRequest(context,url);
//in case of image
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile( ).getName() , ContentType.IMAGE_JPEG);
//in case of audio
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.AUDIO_M3U);
//in case of video
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.VIDEO_MPEG);
//custom parameters if any
request.addParameter("userId",item.userID);
//progress on notification bar
request.setNotificationConfig(R.drawable.ic_launcher,
"Uploading Files",
"Upload in Progress",
"Upload Completed Successfully",
"Error in Uploading",
false);
try {
UploadService.startUpload(request);
} catch (Exception exc) {
exc.printStackTrace();
}
}

Android: How to get image from remote server

I am developing an Android app that should get an image from remote server. Am using WAMP as my server and PHP as programming language. I know how to get text data using JSON.
Am not using blob to store image.
Images have stored in a folder on server. Url of image is stored in db table.
I tried the following snippet, I got this from net but it is not giving any error and also it is not displaying image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
String base64Image = jsonObj.getString("pprs");
Toast.makeText(getBaseContext(), base64Image, Toast.LENGTH_LONG).show();
byte[] rawImage = Base64.decode(base64Image, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
}
}
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
if($row = mysql_fetch_assoc($query))
{
$response = $row['imageUrl'];
}
$response = base64_encode($response);
echo '{"pprs":'.json_encode($response).'}';
mysqli_close($con);
?>
I checked my php code with html(with out encoding $response value) am getting image there, but not in Android.
I am not good with Php, but if you return the file url via a JSON reponse you can use the following code for downloading the file.
int count;
try {
URL url = new URL("http://url of your file");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
## Edit ##
After the Image is downloaded you can create a Bitmap from the Image Path/InputStream and assign it to the Image View like this
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
Original source
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
bitmapPath = jsonObj.getString("pprs");
}
}
try {
Toast.makeText(getBaseContext(), "http://10.0.2.2/sareesProject/"+bitmapPath, Toast.LENGTH_SHORT).show();
URL url = new URL("http://10.0.2.2/sareesProject/"+bitmapPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
bmp = myBitmap;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(bmp == null)
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
//new HomePage().show("in con");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
//show(line);
//new HomePage().show("in while");
//new HomePage().show("l="+line);
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(, text, duration)
} finally {
try {
if(reader != null)
{
try{reader.close();}
catch(Exception e){e.printStackTrace();}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//end of convertStreamToString
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
$response = array();
while($row = mysql_fetch_assoc($query))
{
$response[] = $row['imageUrl'];
}
echo json_encode($response);
mysqli_close($con);
?>
//--------------------
Fnally i got it.............
First of all my server file returns the following
{"pprs":"upload/22.png"}
from this i extracted upload/22.png using JSON
Now bitmapPath contains upload/22.png
Thank you very much to insomniac giving suggestions.............
If it is helpful to any one vote for me..............

Categories