Cant Upload File - NoClassDefFoundError: Commons IO ByteArrayOutputStream

Cant Upload File - NoClassDefFoundError: Commons IO ByteArrayOutputStream

我正在尝试上传我正在使用 AsyncTask 的文件,应用程序 运行 正常,直到我单击上传按钮(在 UploadActivity.java 中定义)应用程序停止。这是 logcat.

**注意:**我已经通过 logcat 提到了给定异常的行号。

    FATAL EXCEPTION: AsyncTask #1 
  java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                  at android.os.AsyncTask.done(AsyncTask.java:299)
                                                                                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
                                                                                  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
                                                                                  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
                                                                                  at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
                                                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                                                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                                                                                  at java.lang.Thread.run(Thread.java:841)
                                                                               Caused by: java.lang.NoClassDefFoundError: org.apache.commons.io.output.ByteArrayOutputStream
                                                                                  at org.apache.http.entity.mime.HttpMultipart.getTotalLength(HttpMultipart.java:219)
                                                                                  at org.apache.http.entity.mime.MultipartEntity.getContentLength(MultipartEntity.java:150)
                                                                                  at com.example.imtiaz.recognizer.UploadActivity$UploadFileToServer.UploadFile(UploadActivity.java:129)
                                                                                  at com.example.imtiaz.recognizer.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:108)
                                                                                  at com.example.imtiaz.recognizer.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:90)
                                                                                  at android.os.AsyncTask.call(AsyncTask.java:287)
                                                                                  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                                                                                  at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
                                                                                  at java.lang.Thread.run(Thread.java:841)

这是 UploadActivity.java 代码。

    public class UploadActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private ProgressBar progressBar;
    private String filePath = null;
    private ImageView imgPreview;
    private Button btnUpload;
    long totalSize = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);

        btnUpload = (Button) findViewById(R.id.btnUpload);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        imgPreview = (ImageView) findViewById(R.id.imageView);

        // Receiving the data from previous activity
        Intent i = getIntent();

        filePath = i.getStringExtra("filePath");
        // boolean flag to identify the media type,
        boolean isImage = i.getBooleanExtra("isImage", true);
        if (filePath != null) {
            // Displaying the image on the screen
            previewMedia(isImage);

        } else {
            Toast.makeText(getApplicationContext(),
                    filePath + "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
        }
        //Creating EventListener.
        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // uploading the file to server
                new UploadFileToServer().execute();
            }
        });
    }

    private void previewMedia(boolean isImage) {
        //Checking mediaType is image or not
        if (isImage) {
            imgPreview.setVisibility(View.VISIBLE);
            //Reducing image size.
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            //Bitmaping image .
            final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
            imgPreview.setImageBitmap(bitmap);

        }
    }

    //else give message media type is not image.
    private class UploadFileToServer extends AsyncTask<Void, Integer, String>//Line 90
{
        @Override
        protected void onPreExecute() {
            progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            //set view to true.
            progressBar.setVisibility(View.VISIBLE);
            //ProgressBar value.
            progressBar.setProgress(progress[0]);
        }

        @Override
        protected String doInBackground(Void... Params) {
            //do background task (UploadFile).
            return UploadFile();//Line 108
        }

        @SuppressWarnings("deprecation")
        private String UploadFile() {
            String responseString = null;
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

            try {
                AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                        new ProgressListener() {
                            @Override
                            public void transferred(long num) {
                                publishProgress((int) (num / (float) totalSize) * 100);
                            }
                        });

                File sourceFile = new File(filePath);
                //Adding File Data to Http BOdy.
                entity.addPart("image", new FileBody(sourceFile));
                totalSize = entity.getContentLength();//Line 129
                httppost.setEntity(entity);
                //Making Server calls.
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity r_entity = response.getEntity();

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    //Server Response.
                    responseString = EntityUtils.toString(r_entity);

                } else {

                    responseString = "Error Occurred Status: " + statusCode;
                }

            } catch (ClientProtocolException e) {
                responseString = e.toString();
            } catch (IOException e) {

                responseString = e.toString();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.e(TAG, "Response from server : " + result);
             //Showing Response.
            showAlert(result);
            super.onPostExecute(result);
        }
    }

    private void showAlert(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle("Response from Servers")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

}

依赖关系

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile files('libs/httpclient-4.0.jar')
compile files('libs/httpcore-4.0-alpha5.jar')
compile files('libs/apache-mime4j-0.3.jar')
compile files('libs/commons-io-2.5.jar')}

您缺少依赖项:

compile group: 'commons-io', name: 'commons-io', version: '2.5'

你需要common-io jar来解决这个问题从Here

下载

下载后转到您的项目,通过 lib 文件夹中的 jar,右键单击它(commons-io.jar)并 select 添加为库,这应该可以解决问题。