简体   繁体   中英

Upload Image taken with camera through php to webpage from android with AsyncTask

I'm trying to upload an image to a weabpage through a PHP but its the first time so I'm having some difficultys. The image that I want to upload should be an image that has been caputed with the camera. So, I have one button to captue an Image, and one button to upload (Post), see code.

I now have 2 problems. 1) The image doesn't get uploaded to the page. 2) the camera works as it should but after I've used it, the post button, or to take a new picture doesn't work.

See below for MainActivity.java, activity_main.xml and the php. (I have internet and camera permissions in my manifest)

I would be very grateful if someone should help me!

MainActivity.java:

public class MainActivity extends ActionBarActivity implements LocationListener {

Button Post, TakePic;

private static int RESULT_LOAD_IMAGE = 1;
ImageView imgView;

@Override
protected void onCreate(Bundle savedInstanceStatea) {
    super.onCreate(savedInstanceStatea);
    setContentView(R.layout.activity_main); 

    final ImageView imgView = (ImageView) findViewById(R.id.imageViewPic);
    Drawable  drawable  = getResources().getDrawable(R.drawable.ic_launcher);
    imgView.setImageDrawable(drawable);

    if (savedInstanceStatea == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new Fragment()).commit();  

        TakePic = (Button) findViewById(R.id.buttonTakePic);
        Post = (Button) findViewById(R.id.buttonPost);

        TakePic.setOnClickListener(new View.OnClickListener() {             
            @Override
            public void onClick(View arg0) {            
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, RESULT_LOAD_IMAGE);
            }
        });             

        Post.setOnClickListener(new View.OnClickListener() {                
            @Override
            public void onClick(View arg0) {
                new UploadImageTask(imgView).execute();  
            }
        });                     
    }
}       

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);         

    if (resultCode == RESULT_OK && null != data) {
        Bitmap picture = (Bitmap) data.getExtras().get("data");                        
        ImageView imageView = (ImageView) findViewById(R.id.imageViewPic);
        imageView.setImageBitmap(picture);          
    }       
}

private class UploadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView imageView = (ImageView) findViewById(R.id.imageViewPic);

    public UploadImageTask(ImageView imgView) {     
    }

    protected Bitmap doInBackground(String... urls) {

        //Fetch the image in the image view
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

        try {  
        //Create a file to put the bitmap on:
        File f = new File("test.jpg");
        f.createNewFile();          

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        byte[] byteArray = bos.toByteArray();

        //write the bytes in file:
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(byteArray);           

          //String fileName = sourceFileUri;          
          HttpURLConnection conns = null;
          DataOutputStream dos = null;
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";

          //open a URL connection to the Server
          URL url = new URL("http:////ADRESS TO MY PAGE.php");

          //Open a HTTP  connection to  the URL
          conns = (HttpURLConnection) url.openConnection(); 
          conns.setDoInput(true);
          conns.setDoOutput(true);
          conns.setUseCaches(false);
          conns.setRequestMethod("POST");
          conns.setRequestProperty("Connection", "Keep-Alive");
          conns.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 

          dos = new DataOutputStream(conns.getOutputStream());

          dos.writeBytes(twoHyphens + boundary + lineEnd);
          dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fos + "\"" + lineEnd);                            
          dos.writeBytes(lineEnd);     

          dos.flush();
          dos.close();
          fos.close();
        } catch (Exception e) {

        }
        return bitmap;          
    }

    protected void onPostExecute(Bitmap result) {
        ImageView imgView = (ImageView) findViewById(R.id.imageViewPic1);
        imgView.setImageBitmap(result);
    }
}

@Override
public void onLocationChanged(Location arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}   
}

activity_main.xml:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame" >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusableInTouchMode="true" >

           <Button
                android:id="@+id/buttonTakePic"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:textColor="#ffffff" 
                android:text="Take picture" />  

           <Button
                android:id="@+id/buttonPost"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:textColor="#ffffff" 
                android:text="POST!" />       

        <ImageView
            android:id="@+id/imageViewPic"
            android:layout_width="match_parent"
            android:layout_margin="5dp"
            android:layout_height="300dp"            
            android:src="@drawable/abc_ab_bottom_transparent_light_holo" />        

        <ImageView
            android:id="@+id/imageViewPic1"
            android:layout_width="match_parent"
            android:layout_margin="5dp"
            android:layout_height="300dp"            
            android:src="@drawable/abc_ab_bottom_transparent_light_holo" />   

    </LinearLayout>

    </ScrollView>

php:

$uploaddir = 'upload/';
$file = basename($_FILES['uploadedfile']['name']);
$uploadfile = $uploaddir . $file;

echo "file=".$file; //is empty, but shouldn't

if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) {
echo $file;
}
else {
echo "error"; 

PHP upload may not work due to execution time and size of file restriction in PHP Server. So try using FTP upload in android.

Example links: http://www.jibble.org/simpleftp/

http://androidexample.com/FTP_File_Upload_From_Sdcard_to_server/index.php?view=article_discription&aid=98&aaid=120

Note: You can do this process in background as well, using AsyncTask.

OR

You can increase the execution time and size for file upload in PHP server as alternative.

Thanks happy coding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM