以下是使用Java代码在Android应用程序中上传图片的示例:

  1. 添加权限

在AndroidManifest.xml文件中添加以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  1. 创建文件选择器

使用以下代码创建文件选择器:

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
  1. 处理文件选择器返回结果

使用以下代码处理文件选择器返回的结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            uploadImage(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 上传图片

使用以下代码将所选图片上传到服务器:

private void uploadImage(Bitmap bitmap) {
    // 将Bitmap转换为字节数组
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();

    // 创建Multipart请求
    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);
    builder.addFormDataPart("image", "image.jpg", RequestBody.create(MediaType.parse("image/jpeg"), imageBytes));

    // 发送请求
    Request request = new Request.Builder()
            .url("http://example.com/upload")
            .post(builder.build())
            .build();

    OkHttpClient client = new OkHttpClient();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            Log.d(TAG, responseBody);
        }
    });
}

注意:在上传图片之前,请确保已经添加了OkHttp库的依赖项

安卓编写程序时如何上传图片请用代码说明

原文地址: https://www.cveoy.top/t/topic/fIWd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录