Android上传下载实现教程

一、流程概述

在Android开发中,实现上传下载功能需要经过以下步骤:

pie
title 上传下载流程
    "Step 1" : 上传文件
    "Step 2" : 下载文件

二、具体步骤

1. 上传文件

  • Step 1: 创建上传文件的UI界面

在布局文件中添加一个选择文件的按钮和一个上传文件的按钮。

<Button
    android:id="@+id/btnSelectFile"
    android:text="选择文件" />

<Button
    android:id="@+id/btnUpload"
    android:text="上传文件" />
  • Step 2: 实现选择文件功能

在Activity中添加代码,实现选择文件的功能。

private static final int SELECT_FILE_REQUEST_CODE = 100;

btnSelectFile.setOnClickListener(v -> {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    startActivityForResult(intent, SELECT_FILE_REQUEST_CODE);
});
  • Step 3: 实现上传文件功能

在Activity中添加代码,实现上传文件的功能。

private void uploadFile(Uri fileUri) {

    // 将文件Uri转换为File对象
    File file = new File(fileUri.getPath());

    // 使用Retrofit2进行文件上传
    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

    // 创建Retrofit实例
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // 创建接口实例
    UploadService service = retrofit.create(UploadService.class);

    // 发起上传请求
    Call<ResponseBody> call = service.uploadFile(body);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            // 上传成功后的处理
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            // 上传失败后的处理
        }
    });
}

2. 下载文件

  • Step 1: 创建下载文件的UI界面

在布局文件中添加一个输入文件下载地址的EditText和一个下载文件的按钮。

<EditText
    android:id="@+id/etDownloadUrl"
    android:hint="输入下载地址" />

<Button
    android:id="@+id/btnDownload"
    android:text="下载文件" />
  • Step 2: 实现下载文件功能

在Activity中添加代码,实现下载文件的功能。

btnDownload.setOnClickListener(v -> {
    String downloadUrl = etDownloadUrl.getText().toString();
    downloadFile(downloadUrl);
});

private void downloadFile(String downloadUrl) {

    // 创建OkHttpClient实例
    OkHttpClient client = new OkHttpClient();

    // 创建请求实例
    Request request = new Request.Builder()
            .url(downloadUrl)
            .build();

    // 发起下载请求
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // 下载失败后的处理
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 下载成功后的处理
            InputStream inputStream = response.body().byteStream();

            // 将输入流写入文件
            File file = new File(Environment.getExternalStorageDirectory(), "downloaded_file");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            fileOutputStream.close();
            inputStream.close();
        }
    });
}

三、总结

通过以上步骤,你可以实现Android上传下载功能。在实际开发中,需要注意文件权限、网络权限等问题,确保功能正常运行。希望这篇教程对你有帮助,祝你在Android开发中取得成功!