android upload progressbarr not working

Posted by pieter on Stack Overflow See other posts from Stack Overflow or by pieter
Published on 2012-09-02T21:03:02Z Indexed on 2012/09/02 21:38 UTC
Read the original article Hit count: 266

Filed under:
|
|

I'm a beginner in Android programming and I was tryinh to upload an image to a server. I found some code here on stackoverflow, I adjusted it and it still doesn't work.

The problem is my image still won't upload.

edit I solved the problem, I had no rights on the folder on the server. Now I have a new problem. the progresbarr doesn't work. it keeps saying 0 % transmitted

does anyone sees an error in my code?

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class PreviewActivity extends Activity {

/** The captured image file. Get it's path from the starting intent */
private File mImage;

public static final String EXTRA_IMAGE_PATH = "extraImagePath"

/** Log tag */
private static final String TAG = "DFH";

/** Progress dialog id */
private static final int UPLOAD_PROGRESS_DIALOG = 0;
private static final int UPLOAD_ERROR_DIALOG = 1;
private static final int UPLOAD_SUCCESS_DIALOG = 2;


/** Handler to confirm button */
private Button mConfirm;

/** Handler to cancel button */
private Button mCancel;

/** Uploading progress dialog */
private ProgressDialog mDialog;


/**
 * Called when the activity is created
 *
 * We load the captured image, and register button callbacks
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.preview);

    setResult(RESULT_CANCELED);

    // Import image
    Bundle extras = getIntent().getExtras();
    String imagePath = extras.getString(FotoActivity.EXTRA_IMAGE_PATH);
    Log.d("DFHprev", imagePath);
    mImage = new File(imagePath);
    if (mImage.exists()) {
        setResult(RESULT_OK);
        loadImage(mImage);
    }

    registerButtonCallbacks();

}

@Override
protected void onPause() {
    super.onPause();

}

/**
 * Register callbacks for ui buttons
 */
protected void registerButtonCallbacks() {
    // Cancel button callback
    mCancel = (Button) findViewById(R.id.preview_send_cancel);
    mCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            PreviewActivity.this.finish();
        }
    });

    // Confirm button callback
    mConfirm = (Button) findViewById(R.id.preview_send_confirm);
    mConfirm.setEnabled(true);
    mConfirm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new UploadImageTask().execute(mImage);
        }
    });
}



/**
 * Initialize the dialogs
 */
@Override
protected Dialog onCreateDialog(int id) {
    switch(id) {
    case UPLOAD_PROGRESS_DIALOG:
        mDialog = new ProgressDialog(this);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setCancelable(false);
        mDialog.setTitle(getString(R.string.progress_dialog_title_connecting));
        return mDialog;


    case UPLOAD_ERROR_DIALOG:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.upload_error_title)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage(R.string.upload_error_message)
                .setCancelable(false)
                .setPositiveButton(getString(R.string.retry), new          DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        PreviewActivity.this.finish();
                    }
                });
        return builder.create();

    case UPLOAD_SUCCESS_DIALOG:
        AlertDialog.Builder success = new AlertDialog.Builder(this);
        success.setTitle(R.string.upload_success_title)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setMessage(R.string.upload_success_message)
                .setCancelable(false)
                .setPositiveButton(getString(R.string.success), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        PreviewActivity.this.finish();
                    }
                });
        return success.create();

    default:
        return null;
    }
}

/**
 * Prepare the progress dialog
 */
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    switch(id) {
    case UPLOAD_PROGRESS_DIALOG:
        mDialog.setProgress(0);
        mDialog.setTitle(getString(R.string.progress_dialog_title_connecting));
    }
}

/**
 * Load the image file into the imageView
 *
 * @param image
 */
protected void loadImage(File image) {
    Bitmap bm = BitmapFactory.decodeFile(image.getPath());
    ImageView view = (ImageView) findViewById(R.id.preview_image);
    view.setImageBitmap(bm);
}

/**
 * Asynchronous task to upload file to server
 */
class UploadImageTask extends AsyncTask<File, Integer, Boolean> {

    /** Upload file to this url */
    private static final String UPLOAD_URL = "http://www.xxxx.x/xxxx/fotos";

    /** Send the file with this form name */
    private static final String FIELD_FILE = "file";


    /**
     * Prepare activity before upload
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        setProgressBarIndeterminateVisibility(true);
        mConfirm.setEnabled(false);
        mCancel.setEnabled(false);
        showDialog(UPLOAD_PROGRESS_DIALOG);
    }

    /**
     * Clean app state after upload is completed
     */
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        setProgressBarIndeterminateVisibility(false);
        mConfirm.setEnabled(true);
        mDialog.dismiss();

        if (result) {
            showDialog(UPLOAD_SUCCESS_DIALOG);
        } else {
            showDialog(UPLOAD_ERROR_DIALOG);
        }
    }

    @Override
    protected Boolean doInBackground(File... image) {
        return doFileUpload(image[0], "UPLOAD_URL");
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        if (values[0] == 0) {
            mDialog.setTitle(getString(R.string.progress_dialog_title_uploading));
        }

        mDialog.setProgress(values[0]);
    }


    private boolean doFileUpload(File file, String uploadUrl) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        String pathToOurFile = file.getPath();
        String urlServer = "http://www.xxxx.x/xxxx/upload.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";

        // log pathtoourfile
        Log.d("DFHinUpl", pathToOurFile);

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        int sentBytes = 0;
        long fileSize = file.length();

        // log filesize
        String files= String.valueOf(fileSize);
        String buffers= String.valueOf(maxBufferSize);
        Log.d("fotosize",files);
        Log.d("buffers",buffers);

        try
        {
        FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

        outputStream = new DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

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

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

        sentBytes += bufferSize;
        publishProgress((int)(sentBytes * 100 / fileSize));

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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



        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        try {
            int responseCode = connection.getResponseCode();
            return responseCode == 200;
        } catch (IOException ioex) {
            Log.e("DFHUPLOAD", "Upload file failed: " + ioex.getMessage(), ioex);
            return false;
        } catch (Exception e) {
            Log.e("DFHUPLOAD", "Upload file failed: " + e.getMessage(), e);
            return false;
        }
        }
        catch (Exception ex)
        {
            String msg= ex.getMessage();
        Log.d("DFHUPLOAD", msg);
        }
        return true;
}

}
}

the PHP code that handles this upload is following:

  <?php
 $date=getdate();

      $urldate=$date['year'].$date['month'].$date['month'].$date['hours'].$date['minutes'].$date[     'seconds'];
 $target_path  = "./";
 $target_path = $target_path . basename( $_FILES['uploadedfile']['name']) . $urldate;
 if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
  echo "The file ".  basename( $_FILES['uploadedfile']['name']).
  " has been uploaded";
 } else{
  echo "There was an error uploading the file, please try again!";
 }
 ?>  

would really appreciate it if someone could help me.

© Stack Overflow or respective owner

Related posts about php

Related posts about android