【问题标题】:Not able to upload camera captured image on server in android无法在android的服务器上上传相机捕获的图像
【发布时间】:2017-09-21 06:38:41
【问题描述】:

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

// 相同的代码

//打开相机的代码

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

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

// 我在尝试从相机上传图像时执行 onFailure。

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

【问题讨论】:

  • 发布错误日志..!!
  • 如果您认为您的代码是正确的,您应该检查您的服务器是否允许上传,还要检查是否有任何上传文件大小限制(同时检查服务器允许的文件扩展名)。我遇到了同样的错误,后来发现这是服务器文件大小限制。
  • 我可以使用图库上传图片,但不能使用相机@AswinPAshok
  • 您不应该从意图数据中获取图像,因为它只是一个微型预览。指定文件保存路径,拍照后从文件中加载图片
  • 您没有将bytes 写入文件。也不创建文件。所以没有文件。您可以使用 File:exists() 进行检查。

标签: android android-camera


【解决方案1】:

根据 cmets :

像这样从画廊或相机中获取图像:

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

使用 ma​​inFile 发送 RequestBody 并像 execMultipartPost(File file) 一样传递

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2020-03-04
    • 2017-09-09
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多