写点什么

鸿蒙开发实现图片上传(上传用户头像)

  • 2025-05-23
    山西
  • 本文字数:3171 字

    阅读完需:约 10 分钟

鸿蒙开发实现图片上传(上传用户头像)

应用场景:




1. 选择图片

1.1. 添加图片到相册中

默认的相册中无法添加图片:windows 模拟器可以通过截图来添加图片

1.2. 选择相册图片

开发者可以通过系统预置的文件选择器(FilePicker),实现该能力。通过 Picker 访问相关文件,将拉起对应的应用,引导用户完成界面操作,接口本身无需申请权限。

import picker from '@ohos.file.picker'; // 一、定义图片选择 Picker 的配置// 实例化 选项对象const photoSelectOptions = new picker.PhotoSelectOptions();// 过滤选择媒体文件类型为IMAGEphotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 选择媒体文件的最大数目photoSelectOptions.maxSelectNumber = 1;   // 二、创建 图片选择对象并选择图片const photoViewPicker = new picker.PhotoViewPicker();// 调用 select 方法,传入选项对象 photoViewPicker.select(photoSelectOptions).then(res=>{    const uri = res.photoUris[0]    // 因为只选了一张    AlertDialog.show({ message: '图片路径为:' + uri }) })
复制代码

2. 拷贝图片到缓存目录

当前上传应用文件功能,仅支持上传应用缓存文件路径(cacheDir)下的文件。

使用上传下载模块,需声明权限:ohos.permission.INTERNET。

应用沙箱目录

使用 fs 模块将上一步的文件,拷贝到 cacheDir 目录下

import fs from '@ohos.file.fs'; // 三.将文件保存到缓存目录(只能上传在缓存目录中的文件)const context = getContext(this)const fileType = 'jpg'// 生成一个新的文件名const fileName = Date.now() + '.' + fileType// 通过缓存路径+文件名 拼接出完整的路径const copyFilePath = context.cacheDir + '/' + fileName// 将文件 拷贝到 临时目录const file = fs.openSync(uri, fs.OpenMode.READ_ONLY)fs.copyFileSync(file.fd, copyFilePath)
复制代码

3. 上传文件

最后,根据接口要求咱们组装数据,并提交给服务器即可

 import request from '@ohos.request';import http from '@ohos.net.http';   // 四、上传图片  // 上传文件  let files: Array<request.File> = [  // internal://cache/ 固定的,后面跟上 咱们上一步拷贝文件名即可  // 【name】 和接口文档的要求对上    { filename: fileName, type: fileType, name: 'img', uri: `internal://cache/${fileName}` }  ]   request.uploadFile(context, {    url: '接口地址', // url 地址    method: 请求方法, // 请求方法    header: {      // 和接口文档的要求的格式对象      contentType: '',    },    files, // 文件信息    data: [] // 额外提交的数据,不能省略  })    .then((res => {      // 这里可以获取到响应的内容      res.on('headerReceive', (value) => {        // body 是 JSON 是响应体        // AlertDialog.show({        //   message: JSON.stringify(value)        // })         // 根据接口文档 转为对应的类型即可         const uploadRes = (value as UploadResponse)        const response = JSON.parse(uploadRes.body) as Response        AlertDialog.show({          message: response.data.url        })        console.log('上传的地址为:', response.data.url)       })    }))
复制代码

完整代码展示:

import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; import request from '@ohos.request';import http from '@ohos.net.http'; // 定义类型interface UploadResponse {  body: string} export interface Response {  /**   * 业务状态码,10000成功, 其他失败   */  code: number;   /**   * 响应数据   */  data: Data;   /**   * 响应消息   */  message: string;} /** * 响应数据 */export interface Data {  /**   * 上传成功的图片-在线地址   */  url: string;}  // 实例化 选项对象const photoSelectOptions = new picker.PhotoSelectOptions();// 过滤选择媒体文件类型为IMAGEphotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;// 选择媒体文件的最大数目photoSelectOptions.maxSelectNumber = 1; @Entry@Componentstruct Page03_uploadImg {  build() {    Navigation() {       Column() {        Image('http://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/ajax/17128585871360.5802423440443907.jpg')        Button('选择并上传图片')          .onClick(() => {            // 创建 图片选择对象            const photoViewPicker = new picker.PhotoViewPicker();            // 调用 select 方法,传入选项对象            photoViewPicker.select(photoSelectOptions)              .then(res => {                const uri = res.photoUris[0]                // 因为只选了一张                // AlertDialog.show({ message: '图片路径为:' + uri })                 // 三、拷贝文件到缓存目录                // 将文件保存到缓存目录(只能上传在缓存目录中的文件)                const context = getContext(this)                const fileType = 'jpg'                // 生成一个新的文件名                const fileName = Date.now() + '.' + fileType                // 通过缓存路径+文件名 拼接出完整的路径                const copyFilePath = context.cacheDir + '/' + fileName                 // 将文件 拷贝到 临时目录                const file = fs.openSync(uri, fs.OpenMode.READ_ONLY)                fs.copyFileSync(file.fd, copyFilePath)                 // 四、上传图片                // 上传文件                let files: Array<request.File> = [                // internal://cache/ 固定的,后面跟上 咱们上一步拷贝文件名即可                // name 和接口文档的要求对上                  { filename: fileName, type: fileType, name: 'img', uri: `internal://cache/${fileName}` }                ]                 request.uploadFile(context, {                  url: 'https://hmajax.itheima.net/api/uploadimg', // url 地址                  method: http.RequestMethod.POST, // 请求方法                  header: {                    // 和接口文档的要求的格式对象                    contentType: 'multipart/form-data',                  },                  files, // 文件信息                  data: [] // 额外提交的数据,不能省略                })                  .then((res => {                    // 这里可以获取到响应的内容                    res.on('headerReceive', (value) => {                      // body 是 JSON                      // AlertDialog.show({                      //   message: JSON.stringify(value)                      // })                       const uploadRes = (value as UploadResponse)                      const response = JSON.parse(uploadRes.body) as Response                      AlertDialog.show({                        message: response.data.url                      })                      console.log('上传的地址为:', response.data.url)                     })                  }))               })           })      }    }    .titleMode(NavigationTitleMode.Mini)    .title('上传图片')   }}
复制代码

#DevEco Studio# #社交 #

用户头像

还未添加个人签名 2025-05-18 加入

还未添加个人简介

评论

发布
暂无评论
鸿蒙开发实现图片上传(上传用户头像)_社交_星河特战队员_InfoQ写作社区