在鸿蒙OS中实现文件上传和下载:详细部署过程

举报
数字扫地僧 发表于 2024/07/25 11:26:23 2024/07/25
1.6k+ 0 0
【摘要】 项目介绍与发展文件上传和下载是现代应用中常见的需求,特别是对于需要处理用户生成内容或与远程服务器交互的应用。在鸿蒙OS(HarmonyOS)中,实现文件上传和下载功能需要利用系统提供的网络库和文件系统 API。本文将详细介绍如何在鸿蒙OS中实现文件上传和下载,包括项目配置、上传下载功能的实现及测试等步骤。蓝图与要求在实现文件上传和下载功能之前,需要了解以下关键概念:I. 文件上传与下载概述:...


项目介绍与发展

文件上传和下载是现代应用中常见的需求,特别是对于需要处理用户生成内容或与远程服务器交互的应用。在鸿蒙OS(HarmonyOS)中,实现文件上传和下载功能需要利用系统提供的网络库和文件系统 API。本文将详细介绍如何在鸿蒙OS中实现文件上传和下载,包括项目配置、上传下载功能的实现及测试等步骤。

蓝图与要求

在实现文件上传和下载功能之前,需要了解以下关键概念:

I. 文件上传与下载概述:理解文件上传和下载的基本流程和需求。 II. 权限配置:确保应用具有文件访问和网络权限。 III. 上传文件实现:如何在鸿蒙OS中实现文件上传功能。 IV. 下载文件实现:如何在鸿蒙OS中实现文件下载功能。 V. 测试与优化:测试上传和下载功能,并进行优化。

实现步骤

I. 创建项目

  1. 创建项目

    • 打开 DevEco Studio,创建一个新的 HarmonyOS 项目,选择“Empty Ability”模板。

  2. 配置权限

    • 在项目的 config.json 配置文件中,添加文件访问和网络权限。

 {
   "module": {
     "reqPermissions": [
       {
         "name": "ohos.permission.INTERNET"
       },
       {
         "name": "ohos.permission.READ_MEDIA"
       },
       {
         "name": "ohos.permission.WRITE_MEDIA"
       }
     ]
   }
 }

II. 实现文件上传功能

  1. 定义布局文件

    • src/main/resources/base/layout 目录下,创建一个布局文件 ability_main.xml,用于实现文件上传的界面。

 <?xml version="1.0" encoding="utf-8"?>
 <DirectionalLayout
     xmlns:ohos="http://schemas.huawei.com/res/ohos"
     ohos:width="match_parent"
     ohos:height="match_parent"
     ohos:orientation="vertical"
     ohos:padding="16vp"><Button
         ohos:id="$+id/button_choose_file"
         ohos:width="match_parent"
         ohos:height="wrap_content"
         ohos:text="Choose File"/><Button
         ohos:id="$+id/button_upload_file"
         ohos:width="match_parent"
         ohos:height="wrap_content"
         ohos:text="Upload File"/><Text
         ohos:id="$+id/text_file_status"
         ohos:width="match_parent"
         ohos:height="wrap_content"
         ohos:textSize="20vp"
         ohos:textColor="#000000"/>
 </DirectionalLayout>
  1. 编写 MainAbilitySlice.java

    • src/main/java/com/example/filetransfer/slice 目录下,创建一个 MainAbilitySlice.java 文件,实现文件选择和上传功能。

 package com.example.filetransfer.slice;import ohos.aafwk.ability.AbilitySlice;
 import ohos.aafwk.content.Intent;
 import ohos.agp.components.Button;
 import ohos.agp.components.Text;
 import ohos.agp.utils.TextAlign;
 import ohos.hiviewdfx.HiLog;
 import ohos.hiviewdfx.HiLogLabel;
 import ohos.hiviewdfx.HiLogWriter;
 import ohos.net.http.HttpClient;
 import ohos.net.http.HttpRequest;
 import ohos.net.http.HttpResponse;
 import ohos.utils.net.Uri;import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.OutputStream;public class MainAbilitySlice extends AbilitySlice {
     private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE, 0x00201, "FileTransfer");
     private Button chooseFileButton;
     private Button uploadFileButton;
     private Text fileStatusText;
     private File selectedFile;
 ​
     @Override
     public void onStart(Intent intent) {
         super.onStart(intent);
         super.setUIContent(ResourceTable.Layout_ability_main);
 ​
         chooseFileButton = (Button) findComponentById(ResourceTable.Id_button_choose_file);
         uploadFileButton = (Button) findComponentById(ResourceTable.Id_button_upload_file);
         fileStatusText = (Text) findComponentById(ResourceTable.Id_text_file_status);
 ​
         chooseFileButton.setClickedListener(component -> chooseFile());
         uploadFileButton.setClickedListener(component -> uploadFile());
     }private void chooseFile() {
         // 打开文件选择器
         Intent intent = new Intent();
         intent.setAction(Intent.ACTION_GET_CONTENT);
         intent.setType("*/*");
         startAbilityForResult(intent, 0);
     }
 ​
     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         if (resultCode == RESULT_OK && data != null) {
             Uri uri = data.getUri();
             selectedFile = new File(uri.getPath());
             fileStatusText.setText("Selected file: " + selectedFile.getName());
         }
     }private void uploadFile() {
         if (selectedFile == null) {
             fileStatusText.setText("No file selected.");
             return;
         }new Thread(() -> {
             try {
                 HttpClient httpClient = new HttpClient();
                 HttpRequest request = new HttpRequest.Builder()
                     .setMethod("POST")
                     .setUri("https://yourserver.com/upload")
                     .build();
 ​
                 request.setHeader("Content-Type", "multipart/form-data; boundary=--boundary");
                 OutputStream outputStream = request.getOutputStream();
 ​
                 FileInputStream fileInputStream = new FileInputStream(selectedFile);
                 byte[] buffer = new byte[1024];
                 int bytesRead;
                 while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                     outputStream.write(buffer, 0, bytesRead);
                 }
 ​
                 fileInputStream.close();
                 outputStream.flush();
                 outputStream.close();
 ​
                 HttpResponse response = httpClient.execute(request);
                 HiLog.info(LABEL, "Upload response: " + response.getStatusCode());
                 fileStatusText.setText("Upload successful.");
             } catch (IOException e) {
                 HiLog.error(LABEL, "Upload failed: " + e.getMessage());
                 fileStatusText.setText("Upload failed.");
             }
         }).start();
     }
 }

III. 实现文件下载功能

  1. 定义布局文件

    • src/main/resources/base/layout 目录下,创建一个布局文件 ability_main_download.xml,用于实现文件下载的界面。

 <?xml version="1.0" encoding="utf-8"?>
 <DirectionalLayout
     xmlns:ohos="http://schemas.huawei.com/res/ohos"
     ohos:width="match_parent"
     ohos:height="match_parent"
     ohos:orientation="vertical"
     ohos:padding="16vp"><Button
         ohos:id="$+id/button_download_file"
         ohos:width="match_parent"
         ohos:height="wrap_content"
         ohos:text="Download File"/><Text
         ohos:id="$+id/text_download_status"
         ohos:width="match_parent"
         ohos:height="wrap_content"
         ohos:textSize="20vp"
         ohos:textColor="#000000"/>
 </DirectionalLayout>
  1. 编写 DownloadAbilitySlice.java

    • src/main/java/com/example/filetransfer/slice 目录下,创建一个 DownloadAbilitySlice.java 文件,实现文件下载功能。

 package com.example.filetransfer.slice;import ohos.aafwk.ability.AbilitySlice;
 import ohos.aafwk.content.Intent;
 import ohos.agp.components.Button;
 import ohos.agp.components.Text;
 import ohos.hiviewdfx.HiLog;
 import ohos.hiviewdfx.HiLogLabel;
 import ohos.net.http.HttpClient;
 import ohos.net.http.HttpRequest;
 import ohos.net.http.HttpResponse;import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;public class DownloadAbilitySlice extends AbilitySlice {
     private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE, 0x00201, "FileTransfer");
     private Button downloadFileButton;
     private Text downloadStatusText;
 ​
     @Override
     public void onStart(Intent intent) {
         super.onStart(intent);
         super.setUIContent(ResourceTable.Layout_ability_main_download);
 ​
         downloadFileButton = (Button) findComponentById(ResourceTable.Id_button_download_file);
         downloadStatusText = (Text) findComponentById(ResourceTable.Id_text_download_status);
 ​
         downloadFileButton.setClickedListener(component -> downloadFile());
     }private void downloadFile() {
         new Thread(() -> {
             try {
                 HttpClient httpClient = new HttpClient();
                 HttpRequest request = new HttpRequest.Builder()
                     .setMethod("GET")
                     .setUri("https://yourserver.com/file-to-download")
                     .build();
 ​
                 HttpResponse response = httpClient.execute(request);
                 InputStream inputStream = response.getInputStream();
                 File file = new File(getFilesDir(), "downloaded-file");
                 FileOutputStream fileOutputStream = new FileOutputStream(file);
 ​
                 byte
 ​
 [] buffer = new byte[1024];
                 int bytesRead;
                 while ((bytesRead = inputStream.read(buffer)) != -1) {
                     fileOutputStream.write(buffer, 0, bytesRead);
                 }
 ​
                 inputStream.close();
                 fileOutputStream.flush();
                 fileOutputStream.close();
 ​
                 HiLog.info(LABEL, "Download completed.");
                 downloadStatusText.setText("Download successful.");
             } catch (IOException e) {
                 HiLog.error(LABEL, "Download failed: " + e.getMessage());
                 downloadStatusText.setText("Download failed.");
             }
         }).start();
     }
 }

IV. 测试与优化

  1. 测试文件上传

    • 在应用中选择一个文件,点击“Upload File”按钮,检查文件是否成功上传到服务器。查看服务器端的日志或响应,确保上传操作正确完成。

  2. 测试文件下载

    • 点击“Download File”按钮,观察文件是否成功下载到设备上指定的目录。可以在文件系统中检查下载的文件是否存在,并确保文件内容正确。

  3. 优化

    • 上传下载性能:考虑使用线程池或异步任务来处理上传和下载操作,以提高性能和响应速度。

    • 错误处理:增加更多的错误处理逻辑,例如处理网络异常、文件读取/写入错误等。

    • 用户体验:提供进度条或其他 UI 元素,让用户了解上传或下载的进度。

代码详细解释

V. 文件上传功能实现

  1. 选择文件

    • 使用 Intent 启动文件选择器,允许用户选择文件。

 private void chooseFile() {
     Intent intent = new Intent();
     intent.setAction(Intent.ACTION_GET_CONTENT);
     intent.setType("*/*");
     startAbilityForResult(intent, 0);
 }
  1. 处理选择的文件

    • onActivityResult 方法中获取选择的文件,并更新 UI 显示文件信息。

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     if (resultCode == RESULT_OK && data != null) {
         Uri uri = data.getUri();
         selectedFile = new File(uri.getPath());
         fileStatusText.setText("Selected file: " + selectedFile.getName());
     }
 }
  1. 上传文件

    • 使用 HttpClient 发送 POST 请求,将文件数据写入请求体。

 private void uploadFile() {
     if (selectedFile == null) {
         fileStatusText.setText("No file selected.");
         return;
     }new Thread(() -> {
         try {
             HttpClient httpClient = new HttpClient();
             HttpRequest request = new HttpRequest.Builder()
                 .setMethod("POST")
                 .setUri("https://yourserver.com/upload")
                 .build();
 ​
             request.setHeader("Content-Type", "multipart/form-data; boundary=--boundary");
             OutputStream outputStream = request.getOutputStream();
 ​
             FileInputStream fileInputStream = new FileInputStream(selectedFile);
             byte[] buffer = new byte[1024];
             int bytesRead;
             while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                 outputStream.write(buffer, 0, bytesRead);
             }
 ​
             fileInputStream.close();
             outputStream.flush();
             outputStream.close();
 ​
             HttpResponse response = httpClient.execute(request);
             HiLog.info(LABEL, "Upload response: " + response.getStatusCode());
             fileStatusText.setText("Upload successful.");
         } catch (IOException e) {
             HiLog.error(LABEL, "Upload failed: " + e.getMessage());
             fileStatusText.setText("Upload failed.");
         }
     }).start();
 }

VI. 文件下载功能实现

  1. 下载文件

    • 使用 HttpClient 发送 GET 请求,获取文件数据并写入本地文件系统。

private void downloadFile() {
    new Thread(() -> {
        try {
            HttpClient httpClient = new HttpClient();
            HttpRequest request = new HttpRequest.Builder()
                .setMethod("GET")
                .setUri("https://yourserver.com/file-to-download")
                .build();

            HttpResponse response = httpClient.execute(request);
            InputStream inputStream = response.getInputStream();
            File file = new File(getFilesDir(), "downloaded-file");
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            inputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            HiLog.info(LABEL, "Download completed.");
            downloadStatusText.setText("Download successful.");
        } catch (IOException e) {
            HiLog.error(LABEL, "Download failed: " + e.getMessage());
            downloadStatusText.setText("Download failed.");
        }
    }).start();
}

项目总结

本文详细介绍了如何在鸿蒙OS中实现文件上传和下载功能。通过创建示例项目,展示了如何配置权限、实现文件选择、上传、下载功能,并提供了测试与优化建议。希望本文能够为您在鸿蒙OS开发中处理文件传输功能提供有价值的参考和帮助。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。