通过multipart将byte []图像上传到服务器

时间:2018-05-25 07:17:56

标签: android camera-view

我正在研究Android上的图片上传功能,我正在使用这两个库: https://github.com/natario1/CameraView

https://github.com/gotev/android-upload-service

所以,根据CameraView库我可以得到我的照片:



mCameraView.addCameraListener(new CameraListener() {
      @Override
      public void onPictureTaken(byte[] jpeg) {
          super.onPictureTaken(jpeg);
      }
});




所以我将我的图片作为字节数组。这里的问题是如何通过multipart将其上传到我的服务器?我有我的后端准备接受文件。 所以我相信我必须将我的byte []转换为文件?

编辑1:对于非常不清楚的问题,很抱歉,问题应该缩小到"如何将byte []写入文件。

2 个答案:

答案 0 :(得分:1)

首先,您必须将您的字节存储到文件中。存储图像后转换为Multipart

File file = new File(fileUri);
            RequestBody reqFile = RequestBody.create(MediaType.parse("image*//*"), file);
            MultipartBody.Part body =  MultipartBody.Part.createFormData(AppConstants.IMAGE, file.getName(), reqFile);


private File saveImage(byte[] bytes, int rotate) {
        try {
            Bitmap bitmap = decodeSampledBitmapFromResource(bytes, bytes.length, 800, 600, rotate);

            return createFile(bitmap);
        } catch (Exception e) {
            Log.e("Picture", "Exception in photoCallback", e);
        }
        return null;
    }

    public Bitmap decodeSampledBitmapFromResource(byte[] bytes, int length, int reqWidth,
                                                  int reqHeight, int rotate) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes, 0, length, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, length, options);
        Bitmap rotatedBitmap = null;
        if (isFrontfaceing) {
            if (rotate == 90 || rotate == 270) {
                rotatedBitmap = rotateImage(bm, -rotate);
            } else {
                rotatedBitmap = rotateImage(bm, rotate);
            }
        } else {
            rotatedBitmap = rotateImage(bm, rotate);
        }
        rotatedBitmap = Bitmap.createScaledBitmap(rotatedBitmap, reqWidth, reqHeight, true);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        return rotatedBitmap;
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,
                                     int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    || (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }


 public File createFile(Bitmap bitmap) {
    File photo =
            new File(getWorkingDirectory().getAbsolutePath()+"yourFileName" + ".jpg");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(photo.getPath());
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return photo;
}

答案 1 :(得分:0)

基本上我们需要的是将byte []写入文件。首先,我为它创建占位符文件。以下是从官方Google文档(https://developer.android.com/training/camera/photobasics#TaskPhotoView

中截取的代码



    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        
        return image;
    }




然后我将byte []写入该文件。



    try {
       File photoFile = createImageFile();
       FileOutputStream fos = new FileOutputStream(photoFile.getPath());
       fos.write(jpeg);
       // then call uploadImage method and pass aboslutePath of my file
       uploadImage(photoFile.getAbsolutePath());
       } catch (IOException e) {}




uploadImage方法根据android-upload-service处理上传:https://github.com/gotev/android-upload-service