将图像上传到服务器时出错(android 无法解码流)

Error in uploading an image to server(android Unable to decode stream)

我正在尝试将图像从我的手机上传到服务器。但是我收到以下错误 "android Unable to decode stream: java.lang.NullPointerException".

这是我的代码供您参考:

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);
        Log.i("picturePath", "picturePath: " + picturePath);
        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 = "URL";

    // 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) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, 100, bos);
        byte[] data = bos.toByteArray();
        String file = Base64.encodeToString(data, 0);

        ArrayList<NameValuePair> postData;
        postData = new ArrayList<NameValuePair>();

        JSONObject parentData = new JSONObject();
        JSONObject childData = new JSONObject();

        try {

            childData.put("fileContent", file);
            childData.put("fileName", "droid.jpeg");
            childData.put("fileType", "I");

            System.out.println(childData);

            parentData.put("mobile", childData);

            System.out.println(parentData);

            postData.add(new BasicNameValuePair("mobile", childData
                    .toString()));

            InputStream is = null;
            String jsonResponse = "";
            JSONObject jObj = null;

        } catch (JSONException e) {
            e.printStackTrace();
        }

        postData.add(new BasicNameValuePair("mobile", childData.toString()));

        InputStream is = null;
        String jsonResponse = "";
        JSONObject jObj = null;

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(webAddressToPost);

            /*
             * MultipartEntity entity = new MultipartEntity(
             * HttpMultipartMode.BROWSER_COMPATIBLE);
             * 
             * entity.addPart("uploaded", new StringBody(file));
             * 
             * entity.addPart("someOtherStringToSend", new StringBody(
             * "your string here"));
             */

            httpPost.setHeader("Content-Type",
                    "application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(parentData.toString()));

            // httpPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            System.out.println(httpResponse);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity()
                            .getContent(), "UTF-8"));

            String sResponse = reader.readLine();
            Log.i("sResponse", "sResponse: " + sResponse);
            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();
    }

}

}

请帮我解决这个问题。我从以下 link

中获取了这段代码

这是我的 log 供您参考。

试试吧。

http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106

希望它的工作。

从您的日志可以看出,问题出在您检索的路径上。

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

        }

使用此代码从您获得的 URI 中获取路径。 您从 onAcvitityResult 获取 uri 作为 Uri selectedImage = data.getData(); 将该 uri 传递给该 getPath 并获取路径。 我正在使用它,它工作正常