Android上传图片到服务器

1. 简介

在现代移动应用中,用户上传图片的功能越来越常见。Android提供了许多方法来实现将图片上传到服务器的功能。本文将介绍一种简单的方法,通过使用HTTP POST请求将图片上传到服务器。

2. 实现步骤

2.1 添加网络权限

首先,在AndroidManifest.xml文件中添加网络权限,以便应用能够访问网络。

<uses-permission android:name="android.permission.INTERNET" />

2.2 选择图片

用户需要选择要上传的图片。可以使用Android的图片选择器,如在Activity中使用Intent.ACTION_PICK来选择图片。

private static final int PICK_IMAGE_REQUEST = 1;

private void selectImage() {
    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

@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 imageUri = data.getData();
        // 在这里处理选择的图片
    }
}

2.3 将图片转换为字节数组

选择图片后,需要将图片转换为字节数组,以便在HTTP请求中发送。

private byte[] convertImageToByteArray(Uri imageUri) throws IOException {
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
}

2.4 发送HTTP请求

现在,我们可以将图片转换为字节数组,并通过HTTP POST请求发送给服务器。

private void uploadImage(byte[] imageBytes) throws IOException {
    String url = " // 替换为实际的服务器URL
    String boundary = "----Boundary" + System.currentTimeMillis();
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

    OutputStream outputStream = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));

    writer.append("--").append(boundary).append("\r\n");
    writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"").append("\r\n");
    writer.append("Content-Type: image/jpeg").append("\r\n");
    writer.append("\r\n");
    outputStream.write(imageBytes);
    writer.append("\r\n").flush();

    writer.append("--").append(boundary).append("--").append("\r\n");
    writer.close();

    int responseCode = connection.getResponseCode();
    // 处理服务器响应
}

2.5 处理服务器响应

根据服务器返回的响应代码,可以确定图片是否成功上传到服务器。

if (responseCode == HttpURLConnection.HTTP_OK) {
    // 图片上传成功
} else {
    // 图片上传失败
}

3. 完整代码

下面是完整的示例代码:

public class UploadImageActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1;

    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @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 imageUri = data.getData();
            try {
                byte[] imageBytes = convertImageToByteArray(imageUri);
                uploadImage(imageBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private byte[] convertImageToByteArray(Uri imageUri) throws IOException {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    private void uploadImage(byte[] imageBytes) throws IOException {
        String url = " // 替换为实际的服务器URL
        String boundary = "----Boundary" + System.currentTimeMillis();
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        OutputStream outputStream = connection.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output