0

我有 EditProfilAcitivity 如果我单击 imageview 将从图库中选择并且没有问题。我有问题 id 我点击按钮上传。

    package net.drieanto.lagidimana;

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.MalformedURLException;
import java.net.URL;

import net.drieanto.lagidimana.library.AlertDialogManager;
import net.drieanto.lagidimana.library.ConnectionDetector;
import net.drieanto.lagidimana.library.UserFunctions;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class EditProfileActivity extends Activity {
    UserFunctions userFunctions;
    Button btnLogout, buttonsearch;
    EditText editSearch;

    private ListView list;
    private ArrayAdapter<String> adapter;
    private RibbonMenuView rbmView;
    private Button test;
    private ListView rbmListView;
    private ListView rbmListView2;
    private ArrayAdapter<String> adapt;
    private ArrayAdapter<String> adapter2;

    ListView list1;
    LazyAdapter adapter1;
    private static int RESULT_LOAD_IMAGE = 1;
    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();
    // Connection detector
    ConnectionDetector cd;
    String selectedPath = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * Dashboard Screen for the application
         * */
        // Check login status in database
        userFunctions = new UserFunctions();
        if (userFunctions.isUserLoggedIn(getApplicationContext())) {
            setContentView(R.layout.editprofile);
            if (android.os.Build.VERSION.SDK_INT >= 11){
                ActionBar bar = getActionBar();
                bar.setBackgroundDrawable(new ColorDrawable(Color.rgb(254,194,12)));
                int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
                TextView actionBarTextView = (TextView)findViewById(actionBarTitleId);
                actionBarTextView.setTypeface(null, Typeface.BOLD);
            }
            // Check if Internet present
            cd = new ConnectionDetector(getApplicationContext());
            if (!cd.isConnectingToInternet()) {
                // Internet Connection is not present
                alert.showAlertDialog(EditProfileActivity.this,
                        "Internet Connection Error",
                        "Please connect to working Internet connection", false);
                // stop executing code by return
                return;
            }
            /** Menu **/
            rbmView = (RibbonMenuView) findViewById(R.id.ribbonMenuView1);
            list = (ListView) findViewById(R.id.listView1);

            ProgressDialog progressDialog = new ProgressDialog(
                    EditProfileActivity.this);
            progressDialog.setMessage("Loading...");
            EditProfileTask EditProfileTask = new EditProfileTask(
                    EditProfileActivity.this, progressDialog);
            EditProfileTask.execute();

            ImageView image = (ImageView) findViewById(R.id.gambarAvatar);
            image.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent i = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(i, RESULT_LOAD_IMAGE);
                }
            });

            editSearch = (EditText) findViewById(R.id.search);
            buttonsearch = (Button) findViewById(R.id.buttonsearch);
            buttonsearch.setOnClickListener(new View.OnClickListener() {

                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent search = new Intent(getApplicationContext(),
                            SearchActivity.class);
                    search.putExtra("data", editSearch.getText().toString());
                    search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(search);
                    finish();
                }
            });

            /**
             * This is an exmaple button it calls "hideMenu()" after each click
             * similiar to the Facebook or Google+ apps
             * **/

            btnLogout = (Button) findViewById(R.id.buttonLogout);
            btnLogout.setOnClickListener(new View.OnClickListener() {

                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    userFunctions.logoutUser(getApplicationContext());
                    Intent login = new Intent(getApplicationContext(),
                            LoginActivity.class);
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    // Closing dashboard screen
                    finish();
                }
            });

            /**
             * This is the most important ListView, updating the main list in
             * the Activity
             **/
            final String[] items_list = { "Home", "Follower", "Request", "View Profile" };
            adapt = new ArrayAdapter<String>(EditProfileActivity.this,
                    android.R.layout.simple_list_item_1, items_list);
            rbmListView = (ListView) findViewById(R.id.rbm_listview);
            rbmListView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    switch (position) {
                    case 0:
                        Intent dashboard = new Intent(getApplicationContext(),
                                DashboardActivity.class);
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        finish();
                        break;

                    case 1:
                        Intent follower = new Intent(getApplicationContext(),
                                FollowerActivity.class);
                        follower.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(follower);
                        finish();
                        break;

                    case 2:
                        Intent request = new Intent(getApplicationContext(),
                                RequestActivity.class);
                        request.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(request);
                        finish();
                        break;

                    case 3:
                        Intent profil = new Intent(getApplicationContext(),
                                ProfilActivity.class);
                        profil.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(profil);
                        // Closing dashboard screen
                        finish();
                        break;

                    default:
                        break;
                    }
                    rbmView.hideMenu();
                }
            });
            rbmListView.setAdapter(adapt);

        } else {
            // user is not logged in show login screen
            Intent login = new Intent(getApplicationContext(),
                    LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            // Closing dashboard screen
            finish();
        }
        Button upload = (Button)findViewById(R.id.imguploadbtn);
        upload.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new ImageUpload().execute();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaColumns.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            selectedPath = getPath(selectedImage);
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            final String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.gambarAvatar);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }

    }

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

    /*private void doFileUpload(){
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "rn";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = "http://git.drieanto.net/upload/upload.php";
        try
        {
         //------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
         // open a URL connection to the Servlet
         URL url = new URL(urlString);
         // 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=\"uploadedfile\";filename=\"" + selectedPath + "\"" + 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);
         // close streams
         Log.e("Debug","File is written");
         fileInputStream.close();
         dos.flush();
         dos.close();
        }
        catch (MalformedURLException ex)
        {
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe)
        {
             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);
              }
              inStream.close();

        }
        catch (IOException ioex){
             Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
      }*/

    /**
     * Allows users, even API < 5, to use the back button
     * 
     * public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode)
     * { case KeyEvent.KEYCODE_BACK: rbmView.hideMenu(); break; default: return
     * super.onKeyDown(keyCode, event); } return true; }
     */
    /**
     * Options Menu<br>
     * example toggle
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.test:
            rbmView.toggleMenu();
            break;

        default:
            return super.onOptionsItemSelected(item);
        }
        return true;
    }

    public void showEditError(int responseCode) {
        int duration = Toast.LENGTH_LONG;
        Context context = getApplicationContext();
        Toast toast = Toast.makeText(context, "Terjadi Error", duration);
        toast.show();
    }

    public void showEditSuccess(int responseCode) {
        int duration = Toast.LENGTH_LONG;
        Context context = getApplicationContext();
        Toast toast = Toast.makeText(context, "Terjadi Error", duration);
        toast.show();
    }

    class ImageUpload extends AsyncTask<Void, Void, String>{
        @Override
        protected void onProgressUpdate(Void... unsued) {

        }

        @Override
        protected String doInBackground(Void... params) {
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            DataInputStream inStream = null;
            String lineEnd = "rn";
            String twoHyphens = "--";
            String boundary =  "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;
            String responseFromServer = "";
            String urlString = "http://lagidimana.net/upload/upload.php";
            try
            {
             //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
             // open a URL connection to the Servlet
             URL url = new URL(urlString);
             // 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=\"uploadedfile\";filename=\"" + selectedPath + "\"" + 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);
             // close streams
             Log.e("Debug","File is written");
             fileInputStream.close();
             dos.flush();
             dos.close();
            }
            catch (MalformedURLException ex)
            {
                 Log.e("Debug", "error: " + ex.getMessage(), ex);
            }
            catch (IOException ioe)
            {
                 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);
                  }
                  inStream.close();

            }
            catch (IOException ioex){
                 Log.e("Debug", "error: " + ioex.getMessage(), ioex);
            }
            return null;
        }

    }
}

上传.php文件

<?php
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

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!";
    echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
    echo "target_path: " .$target_path;
}
?>

我有 chmod 777 文件夹上传/

底部 logcat 中的错误消息,但我不明白这个错误。也许你有同样的问题。

06-14 21:46:35.339: E/Debug(13682): File is written
06-14 21:46:53.339: E/Debug(13682): Server Response There was an error uploading the file, please try again!filename: target_path: uploads/

请帮忙谢谢

4

1 回答 1

0

您正在从主 UI 线程调用函数 doFileUpload。Android 不允许您在主线程上进行网络调用。

构建一个 Asynctask 并执行从另一个线程连接到网络的上传过程(在 doInBackground 函数中)。

于 2013-06-14T14:18:53.473 回答