无法在Android上的服务器上传摄像头捕获的图像

时间:2017-09-21 06:38:41

标签: android android-camera

我正在开发一个应用程序,我想从图库或相机中获取图像,然后使用multipart将其发送到服务器。我可以将图片从图库发送到服务器,但是当我尝试从相机发送图像时,它显示我失败了。

//相同的代码

//打开相机的代码

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

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


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

//发送到服务器代码

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

//尝试从相机上传图片时,我正在执行失败。

    @Override public void getItemOffsets(
        Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    int l, t, r, b;
    l = leftMargin;
    t = topMargin;
    r = rightMargin;
    b = bottomMargin;
    if (mIgnoreAfterLast && parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
        if (mHorizontal) {
            r = 0;
        } else {
            b = 0;
        }
    }
    if (mIgnoreBeforeFirst && parent.getChildAdapterPosition(view) == 0) {
        if (mHorizontal) {
            l = 0;
        } else {
            t = 0;
        }
    }
    outRect.set(l, t, r, b);
}

1 个答案:

答案 0 :(得分:0)

根据评论:

从图库或相机中获取图像:

File mainFile = null;
Bitmap bitmap = (Bitmap) data.getExtras().get("data");

String partFilename = currentDateFormat();
mainFile = storeCameraPhotoInSDCard(bitmap, partFilename);



public String currentDateFormat() {
    String currentTimeStamp = null;
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
        currentTimeStamp = dateFormat.format(new Date());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return currentTimeStamp;
}

public File storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate) {
    File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outputFile;
}

使用 mainFile 发送 RequestBody 并传递 execMultipartPost(文件文件)