鸿蒙NEXT使用request模块实现本地文件上传
大家好,我是 V 哥。在鸿蒙 NEXT API 12 中,可以使用 ohos.request
模块提供的上传接口将本地文件上传到服务器。自定义代理设置可以通过 request.agent.create
接口来实现,从而指定代理服务器的地址。下面是一个详细的案例代码,演示了如何使用自定义代理上传本地文件。整理好的学习笔记,分享给大家。
示例代码
import { request } from **********'; import { Log } from **********'; import fs from **********'; export default { data: { localFilePath: '/data/files/example.txt', // 需要上传的文件路径 serverUrl: 'https://example.com/upload', // 上传文件的服务器URL proxyUrl: 'http://proxy.example.com:8080', // 自定义代理地址 }, onInit() { // 在组件初始化时,触发上传文件的操作 this.uploadFileWithProxy(); }, async uploadFileWithProxy() { try { // 创建代理代理服务 const agent = await request.agent.create({ proxy: this.proxyUrl, // 设置自定义代理地址 }); Log.info('Custom proxy agent created successfully.'); // 读取本地文件 const fileData = await this.readFile(this.data.localFilePath); if (!fileData) { Log.error('Failed to read local file.'); return; } // 准备上传请求的参数 const options = { url: this.data.serverUrl, // 目标上传URL method: 'POST', // HTTP方法为POST headers: { 'Content-Type': 'multipart/form-data', // 设置请求头 }, data: { file: fileData, // 上传的文件内容 }, agent, // 使用代理 }; // 发起文件上传请求 const response = await request.upload(options); if (response && response.status === 200) { Log.info('File uploaded successfully: ' + JSON.stringify(response)); } else { Log.error('File upload failed: ' + JSON.stringify(response)); } } catch (error) { Log.error('Error during file upload: ' + error.message); } }, // 读取本地文件内容的函数 async readFile(filePath: string) { try { // 读取本地文件 const fileStats = await fs.stat(filePath); if (!fileStats || !fileStats.isFile) { return null; // 文件不存在或不是一个文件 } const fileData = await fs.readFile(filePath); return fileData; } catch (error) { Log.error('Error reading file: ' + error.message); return null; } }, };
解释:
- 代理服务创建 (
request.agent.create
): - 读取本地文件:
- 上传文件:
- 日志:
需要注意:
request.upload
方法是鸿蒙系统提供的用于上传文件的接口。确保传递正确的options
,包括文件内容、上传URL等。- 代理的地址通过
request.agent.create
设置,可以为HTTP请求指定一个中间代理服务器,尤其在网络受限或者有特殊需求时非常有用。 - 需要正确配置服务器端接收文件的接口(如
POST
方法和表单数据处理)。 - 将需要上传的文件路径替换为你本地实际存在的文件路径(如
/data/files/example.txt
)。 - 确保服务器端能够处理来自代理服务器的上传请求。
- 使用合适的
proxyUrl
进行自定义代理。
此示例提供了一个基础框架,你可以根据实际需求扩展或修改功能,感谢支持,关注威哥爱编程,一起学鸿蒙开发。
#鸿蒙#威哥鸿蒙原创技术栈 文章被收录于专栏
专注于鸿蒙技术原创分享