Uploading Image from Android to PHP Server

Uploading Image from android to PHP server

Use below code. It will do the same.

public class UploadImage extends Activity {
InputStream inputStream;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon); ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("image",image_str));

Thread t = new Thread(new Runnable() {

@Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("server-link/folder-name/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
});

}catch(Exception e){
runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
System.out.println("Error in http connection "+e.toString());
}
}
});
t.start();
}

public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
}
});

if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..

runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
}
});
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}

PHP Code

<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>

UPDATE

NameValuePair and Http Classes are deprecated so, I've tried this code and it's working for me. Hope that helps!

private void uploadImage(Bitmap imageBitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] b = stream.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
ArrayList<Pair<String, String>> params = new ArrayList<Pair<String, String>>();
params.add(new Pair<>("image", encodedImage));

try {
new AsyncUploader().execute(my_upload_php, getQuery(params));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

private String getQuery(List<Pair<String, String>> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;

for(Pair<String, String> pair : params){
if(first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(pair.first, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.second, "UTF-8"));
}
return result.toString();
}

private class AsyncUploader extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... strings) {
String urlString = strings[0];
String params = strings[1];
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);

urlConnection.connect();

OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(params);
wr.flush();

stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
return result;
}catch (IOException ioe){
ioe.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return null;
}

@Override
protected void onPostExecute(String result) {
Toast.makeText(MakePhoto.this, result, Toast.LENGTH_SHORT).show();
}
}

Uploading file in php server from android device

I don't know about your code but providing you both working codes:
This is for all types of files. I used it for image, audio and for video files.

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) {
}
}

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.";
}

?>

Android : Upload image to PHP server

Have you verified that the user apache (or whichever user php is running as) has permissions to write to the directory specified in $file_path?

Put the following code in the same directory as your PHP script is, and then visit it in your web browser.

<?php

$file_path = 'uploads/';

$success = file_put_contents($file_path . "afile", "This is a test");

if($success === false) {
echo "Couldn't write file";
} else {
echo "Wrote $success bytes";
}

?>

Does this give a success message or an error message?

If it gives an error message, trying changing the ownership of the uploads directory.



Related Topics



Leave a reply



Submit