Php 尝试将图片上载到服务器时,应用程序被迫关闭

Php 尝试将图片上载到服务器时,应用程序被迫关闭,php,android,Php,Android,我从一个网站上复制了这个示例,我不知道为什么这个示例不起作用。 我的预期流程是:我从图库中挑选一张图片,在imageview中显示,然后将其上传到服务器 前两步——挑选一张图片并展示——工作正常,但当我点击上传按钮时,我的应用程序被迫关闭,即运行时错误。我认为php文件可能有问题,但使用方法不确定 如果需要解决我的问题,您可以询问更多信息 package com.example.imagepickanduplaod; public class MainActivity extends Acti

我从一个网站上复制了这个示例,我不知道为什么这个示例不起作用。

我的预期流程是:我从图库中挑选一张图片,在imageview中显示,然后将其上传到服务器

前两步——挑选一张图片并展示——工作正常,但当我点击上传按钮时,我的应用程序被迫关闭,即运行时错误。我认为php文件可能有问题,但使用方法不确定

如果需要解决我的问题,您可以询问更多信息

package com.example.imagepickanduplaod;

public class MainActivity extends Activity {

    private ImageView image;
    private Button uploadButton;
    private Bitmap bitmap;
    private Button selectImageButton;

    // number of images to select
    private static final int PICK_IMAGE = 1;

    /**
     * called when the activity is first created
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // find the views
        image = (ImageView) findViewById(R.id.uploadImage);
        uploadButton = (Button) findViewById(R.id.uploadButton);

        // on click select an image
        selectImageButton = (Button) findViewById(R.id.selectImageButton);
        selectImageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                selectImageFromGallery();

            }
        });

        // when uploadButton is clicked
        uploadButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new ImageUploadTask().execute();
            }
        });
    }

    /**
     * Opens dialog picker, so the user can select image from the gallery. The
     * result is returned in the method <code>onActivityResult()</code>
     */
    public void selectImageFromGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                PICK_IMAGE);
    }

    /**
     * Retrives the result returned from selecting image, by invoking the method
     * <code>selectImageFromGallery()</code>
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            decodeFile(picturePath);

        }
    }

    /**
     * The method decodes the image file to avoid out of memory issues. Sets the
     * selected image in to the ImageView.
     * 
     * @param filePath
     */
    public void decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);

        image.setImageBitmap(bitmap);
    }

    /**
     * The class connects with server and uploads the photo
     * 
     * 
     */
    class ImageUploadTask extends AsyncTask<Void, Void, String> {
        private String webAddressToPost = "http://menaria.zz.mu/picupload.php";

        // private ProgressDialog dialog;
        private ProgressDialog dialog = new ProgressDialog(MainActivity.this);

        @Override
        protected void onPreExecute() {
            dialog.setMessage("Uploading...");
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(webAddressToPost);

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                String file = Base64.encodeBytes(data);
                entity.addPart("uploaded", new StringBody(file));

                entity.addPart("someOtherStringToSend", new StringBody(
                        "your string here"));

                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

                String sResponse = reader.readLine();
                return sResponse;
            } catch (Exception e) {
                // something went wrong. connection with the server error
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "file uploaded",
                    Toast.LENGTH_LONG).show();
        }

    }

    }
这是stacktrace

07-11 16:01:17.791: I/Timeline(27694): Timeline: Activity_idle id: android.os.BinderProxy@436a8d70 time:57708003
07-11 16:01:21.111: E/dalvikvm(27694): Could not find class 'org.apache.http.entity.mime.MultipartEntity', referenced from method com.example.imagepickanduplaod.MainActivity$ImageUploadTask.doInBackground
07-11 16:01:21.111: W/dalvikvm(27694): VFY: unable to resolve new-instance 1607 (Lorg/apache/http/entity/mime/MultipartEntity;) in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;
07-11 16:01:21.111: D/dalvikvm(27694): VFY: replacing opcode 0x22 at 0x0011
07-11 16:01:21.111: I/dalvikvm(27694): DexOpt: unable to optimize static field ref 0x14d2 at 0x13 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.111: D/dalvikvm(27694): DexOpt: unable to opt direct call 0x3067 at 0x15 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.111: D/dalvikvm(27694): DexOpt: unable to opt direct call 0x3069 at 0x36 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.111: D/dalvikvm(27694): DexOpt: unable to opt direct call 0x3069 at 0x42 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.151: W/dalvikvm(27694): threadid=12: thread exiting with uncaught exception (group=0x41f36d58)
07-11 16:01:21.151: E/AndroidRuntime(27694): FATAL EXCEPTION: AsyncTask #2
07-11 16:01:21.151: E/AndroidRuntime(27694): Process: com.example.imagepickanduplaod, PID: 27694
07-11 16:01:21.151: E/AndroidRuntime(27694): java.lang.RuntimeException: An error occured while executing doInBackground()
07-11 16:01:21.151: E/AndroidRuntime(27694):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.lang.Thread.run(Thread.java:841)
07-11 16:01:21.151: E/AndroidRuntime(27694): Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.mime.MultipartEntity
07-11 16:01:21.151: E/AndroidRuntime(27694):    at com.example.imagepickanduplaod.MainActivity$ImageUploadTask.doInBackground(MainActivity.java:173)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at com.example.imagepickanduplaod.MainActivity$ImageUploadTask.doInBackground(MainActivity.java:1)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-11 16:01:21.151: E/AndroidRuntime(27694):    ... 4 more
07-11 16:01:21.241: I/Process(27694): Sending signal. PID: 27694 SIG: 9
public function saveMobileAttachment($imageFile,$userId,$fileName,$fileDescription){
$newRow = $this->createRow();
$buffer = base64_decode($imageFile);
$date = new Zend_Date();
$currentDate = $date->get();
$newRow->FilePath = "attachments/".$currentDate.".jpg";
$file = fopen("attachments/".$currentDate.".jpg", "wb");
fwrite($file, $buffer);  
fclose($file);
$newRow->FileDescription = $fileDescription;
$newRow->FileName = $fileName;
$userAtch = new UserAttachments();
$userAtchRow = $userAtch->createRow();
$userAtchRow->ImageID = $newRow->save();
$userAtchRow->UserID = $userId;
$userAtchRow->save();
}
这是我的php代码

07-11 16:01:17.791: I/Timeline(27694): Timeline: Activity_idle id: android.os.BinderProxy@436a8d70 time:57708003
07-11 16:01:21.111: E/dalvikvm(27694): Could not find class 'org.apache.http.entity.mime.MultipartEntity', referenced from method com.example.imagepickanduplaod.MainActivity$ImageUploadTask.doInBackground
07-11 16:01:21.111: W/dalvikvm(27694): VFY: unable to resolve new-instance 1607 (Lorg/apache/http/entity/mime/MultipartEntity;) in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;
07-11 16:01:21.111: D/dalvikvm(27694): VFY: replacing opcode 0x22 at 0x0011
07-11 16:01:21.111: I/dalvikvm(27694): DexOpt: unable to optimize static field ref 0x14d2 at 0x13 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.111: D/dalvikvm(27694): DexOpt: unable to opt direct call 0x3067 at 0x15 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.111: D/dalvikvm(27694): DexOpt: unable to opt direct call 0x3069 at 0x36 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.111: D/dalvikvm(27694): DexOpt: unable to opt direct call 0x3069 at 0x42 in Lcom/example/imagepickanduplaod/MainActivity$ImageUploadTask;.doInBackground
07-11 16:01:21.151: W/dalvikvm(27694): threadid=12: thread exiting with uncaught exception (group=0x41f36d58)
07-11 16:01:21.151: E/AndroidRuntime(27694): FATAL EXCEPTION: AsyncTask #2
07-11 16:01:21.151: E/AndroidRuntime(27694): Process: com.example.imagepickanduplaod, PID: 27694
07-11 16:01:21.151: E/AndroidRuntime(27694): java.lang.RuntimeException: An error occured while executing doInBackground()
07-11 16:01:21.151: E/AndroidRuntime(27694):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.lang.Thread.run(Thread.java:841)
07-11 16:01:21.151: E/AndroidRuntime(27694): Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.mime.MultipartEntity
07-11 16:01:21.151: E/AndroidRuntime(27694):    at com.example.imagepickanduplaod.MainActivity$ImageUploadTask.doInBackground(MainActivity.java:173)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at com.example.imagepickanduplaod.MainActivity$ImageUploadTask.doInBackground(MainActivity.java:1)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-11 16:01:21.151: E/AndroidRuntime(27694):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-11 16:01:21.151: E/AndroidRuntime(27694):    ... 4 more
07-11 16:01:21.241: I/Process(27694): Sending signal. PID: 27694 SIG: 9
public function saveMobileAttachment($imageFile,$userId,$fileName,$fileDescription){
$newRow = $this->createRow();
$buffer = base64_decode($imageFile);
$date = new Zend_Date();
$currentDate = $date->get();
$newRow->FilePath = "attachments/".$currentDate.".jpg";
$file = fopen("attachments/".$currentDate.".jpg", "wb");
fwrite($file, $buffer);  
fclose($file);
$newRow->FileDescription = $fileDescription;
$newRow->FileName = $fileName;
$userAtch = new UserAttachments();
$userAtchRow = $userAtch->createRow();
$userAtchRow->ImageID = $newRow->save();
$userAtchRow->UserID = $userId;
$userAtchRow->save();
}

NoClassDefFoundError意味着它找不到包含该类的jar

由于您在编译代码时显然没有遇到任何问题,这一定意味着您的APK中没有包含jar

解决方案取决于您如何构建应用程序

如果您使用的是Android Studio,请转到文件->项目结构->应用->依赖项,并确保列出了apache http库jar


如果您使用的是Eclipse,请转到项目->属性->Java构建路径->库->Android依赖项,并确保列出了jar。然后转到“订单和导出”选项卡,确保选中了“Android依赖项”。

我已选中,一切正常,我已添加了所有jar文件,并且选中了“Android依赖项”:(确保你的httpmime.jar和common-io.jar文件在libs folder中,你能告诉我我的php代码应该是什么吗?不知道php代码,但noclassdeferror意味着在你的构建路径中找不到multipartentity类。嗯,我问了关于php代码的新问题,希望我能得到答案:(给出新问题的链接)