2017-09-21 178 views
-1

我正在一个应用程序中,我想从图库或相机中获取图像,然后使用multipart将其发送到服务器。我能够从画廊发送图片到服务器,但是当我试图从相机发送图像时,它显示我失败。对于同一无法上传图像android

//代码来回开相机

 private void cameraIntent() { 
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    startActivityForResult(intent, REQUEST_CAMERA); 

} 

//对活动结果

//代码

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == REQUEST_CAMERA) { 
      Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
      ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
      thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); 
      File destination = new File(Environment.getExternalStorageDirectory(), 
        System.currentTimeMillis() + ".jpg"); 

      Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination)); 

      filePath = destination.toString(); 
      if (filePath != null) { 

       try { 
        execMultipartPost(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } else { 
       Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show(); 
      } 
     } 

//发送到服务器代码

private void execMultipartPost() throws Exception { 

    File file = new File(filePath); 
    String contentType = file.toURL().openConnection().getContentType(); 

    Log.d("TAG", "file new path: " + file.getPath()); 
    Log.d("TAG", "contentType: " + contentType); 


    RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file); 

    final String filename = "file_" + System.currentTimeMillis()/1000L; 



    RequestBody requestBody = new MultipartBody.Builder() 
      .setType(MultipartBody.FORM) 


      .addFormDataPart("date", "21-09-2017") 
      .addFormDataPart("time", "11.56") 
      .addFormDataPart("description", "hello") 
      .addFormDataPart("image", filename + ".jpg", fileBody) 


      .build(); 

    Log.d("TAG", "execMultipartPost: "+requestBody); 

    okhttp3.Request request = new okhttp3.Request.Builder() 
      .url("http://myexample/api/user/lets_send") 
      .post(requestBody) 
      .build(); 

    OkHttpClient okHttpClient = new OkHttpClient(); 


    okHttpClient.newCall(request).enqueue(new Callback() { 
     @Override 
     public void onFailure(Call call, final IOException e) { 
      getActivity().runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 

        Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     } 


     @Override 
     public void onResponse(Call call, final okhttp3.Response response) throws IOException { 
      getActivity().runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        try { 

         Log.d("TAG", "response of image: " + response.body().string()); 

        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 
     } 
    }); 
} 
+0

请问您可以在这里添加错误日志 – UltimateDevil

+0

使用断点将有助于您更好地确定问题。 –

回答

3

请走槽下面的代码

try { 
    if (imageUri != null) { 
     photo = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri)); 
    } else { 
     photo = (Bitmap) data.getExtras().get("data"); 
    } 
    Uri tempUri = CommonData.getImageUri(getContext(), photo); 
    uri = tempUri.toString(); 
    String path = CommonData.convertImageUriToFile(tempUri, getActivity()); 
    //    new PreprocessImagesTask().execute(path); 
    showLoader(); 
    new ProcessingImage(this).execute(path); 

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

} 

public static Uri getImageUri(Context inContext, Bitmap inImage) { 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
    return Uri.parse(path); 
} 

public static String convertImageUriToFile(Uri imageUri, Activity activity) { 
    String imgPath = ""; 
    String Path; 
    try { 
     Cursor cursor = null; 
     int imageID = 0; 

     try { 
      /* ********** Which columns values want to get ****** */ 
      String[] proj = { 
        MediaStore.Images.Media.DATA, 
        MediaStore.Images.Media._ID, 
        MediaStore.Images.Thumbnails._ID, 
        MediaStore.Images.ImageColumns.ORIENTATION 
      }; 

      cursor = activity.getContentResolver().query(

        imageUri, // Get data for specific image URI 
        proj,  // Which columns to return 
        null,  // WHERE clause; which rows to return (all rows) 
        null,  // WHERE clause selection arguments (none) 
        null  // Order-by clause (ascending by name) 

      ); 

      int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      int size = cursor.getCount(); 

      /* ****** If size is 0, there are no images on the SD Card. **** */ 

      if (size == 0) { 
       //    imageDetails.setText("No Image"); 
      } else { 

       int thumbID = 0; 
       if (cursor.moveToFirst()) { 
        Path = cursor.getString(file_ColumnIndex); 
        //String orientation = cursor.getString(orientation_ColumnIndex); 
        String CapturedImageDetails = " CapturedImageDetails : \n\n" 
          + " ImageID :" + imageID + "\n" 
          + " ThumbID :" + thumbID + "\n" 
          + " Path :" + Path + "\n"; 
        showLog("CapturedImageDetails", CapturedImageDetails); 
        imgPath = Path; 
        // Show Captured Image detail on view 
        //     imageDetails.setText(CapturedImageDetails); 

       } 
      } 
     } finally { 
      if (cursor != null) { 
       cursor.close(); 
      } 
     } 

     return "" + imgPath; 
    } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
     return ""; 
    } 
} 
0

试试这个,它可以帮助

Intent takePhotoIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
Date date = new Date(); 
     String timeStamp = new SimpleDateFormat(pictureNameDateFormat, Locale.US).format(date.getTime()); 
    File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/Pictures"); 


if (fileDirectory.exists()) { 
       takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
         new File(Environment.getExternalStorageDirectory() + "/Pictures/picture_"+ timeStamp + ".png"))); 
       takePhotoIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
       takePhotoIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 
       if (takePhotoIntent.resolveActivity(activity.getPackageManager()) != null) { 
        activity.startActivityForResult(takeVideoIntent, captureVideoActivityRequestCode); 
       } 
      } 
0
private void onCaptureImageResult(Intent data) { 
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); 
    File destination = new File(Environment.getExternalStorageDirectory(), 
      System.currentTimeMillis() + ".jpg"); 
    FileOutputStream fo; 
    try { 
     destination.createNewFile(); 
     fo = new FileOutputStream(destination); 
     fo.write(bytes.toByteArray()); 
     fo.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    Log.e("path",Environment.getExternalStorageDirectory(), 
      System.currentTimeMillis() + ".jpg"); 


} 
0

请使用下面的代码通过摄像头和从图库中选择图像,以撷取图片,你还可以裁剪。

首先,请确保您的build.gradle

compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+' 

添加这种依赖在你的活动请添加以下代码:

uploadPic.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) {    
       onSelectImageClick(view); 
      } 
     }); 

/** 
    * Start pick image activity with chooser. 
    */ 
    public void onSelectImageClick(View view) { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 

      if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
       ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_REQUEST_CAMERA); 
      } else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { 
       CropImage.startPickImageActivity(this); 
      } 
     }else { 
      CropImage.startPickImageActivity(this); 
     } 
    } 

@Override 
    @SuppressLint("NewApi") 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     // handle result of pick image chooser 
     if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) { 
      Uri imageUri = CropImage.getPickImageResultUri(this, data); 
      startCropImageActivity(imageUri); 
     } 

     // handle result of CropImageActivity 
     if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { 
      CropImage.ActivityResult result = CropImage.getActivityResult(data); 
      if (resultCode == RESULT_OK) { 
       fileUri = result.getUri(); 
       userImage.setImageURI(result.getUri()); 
       Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show(); 
      } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { 
       Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { 
      CropImage.startPickImageActivity(this); 
     } else { 
      Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show(); 
     } 
    } 

    /** 
    * Start crop image activity for the given image. 
    */ 
    private void startCropImageActivity(Uri imageUri) { 
     CropImage.activity(imageUri) 
       .setGuidelines(CropImageView.Guidelines.ON) 
       .setMultiTouchEnabled(true) 
       .start(this); 
    } 
+0

她没有要求任何图书馆的人。 – UltimateDevil

0

给一试!

private static final int REQUEST_IMAGE = 100; 
private static final String TAG = "MainActivity"; 
TextView imgPath; 
ImageView picture; 
File destination; 
String imagePath; 

//onCreate 

    private void cameraIntent() { 
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination)); 
     startActivityForResult(intent, REQUEST_IMAGE); 
    } 

} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){ 
     try { 
      FileInputStream in = new FileInputStream(destination); 
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inSampleSize = 10; 
      imagePath = destination.getAbsolutePath();//get your path 
      imgPath.setText(imagePath); 
      Bitmap bmp = BitmapFactory.decodeStream(in, null, options); 
      picture.setImageBitmap(bmp); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

    } 
    else{ 
     imgPath.setText("Request cancelled"); 
    } 
} 
0
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 

在清单请加上这些权限,并要求运行时的权限也,这可能会解决你的问题,你的编码是正确的那些作品,我同意加入后完全。