HarmonyOS 鸿蒙Next中上传本地相册中的图片,怎么实现呢? POST请求

HarmonyOS 鸿蒙Next中上传本地相册中的图片,怎么实现呢? POST请求

  1. 目前实现demo如下:发现只能接收到progress和fail的返回结果,是UploadConfig设置的有问题吗?
static async uploadStatusImage(context: Context, uri: string) {
    // uri: file://media/Photo/73/IMG_1726626546_060/screenshot_20240918_102726.jpeg
    let cacheDir = context.cacheDir;
    let path = cacheDir + '/upload_status_image.jpeg'
    
    // 放到临时文件中
    if (FileUtils.exist(path)) {
        FileUtils.deleteFile(path)
    }
    console.error('image-start', path)
    let file = fs.openSync(uri, fs.OpenMode.CREATE);
    fs.copyFileSync(file.fd, path);
    fs.closeSync(file);
    
    // config 定义是否有问题
    let config: request.UploadConfig = {
        header: { "Content-Type": "multipart/form-data", },
        url: 'https://xxxxxxx/xx/photo/upload.json',
        method: 'POST',
        files: [{
            filename: "upload_status_image.jpeg",
            name: "file",
            uri: "internal://cache/upload_status_image.jpeg",
            type: "jpeg"
        }],
        data: [{ name: "upload_status_image", value: "111" }],
    }
    
    console.error('image-upload', path)
    
    request.uploadFile(context, config, (err: BusinessError, task: request.UploadTask) => {
        if (err) {
            console.error(`image-upload() fail ${err.message}`);
            return
        }
        task.on('progress', (receivedSize: number, totalSize: number) => {
            console.error('image- progress', receivedSize, totalSize)
        })
        task.on('complete', (taskStates: Array<request.TaskState>) => {
            console.error('image-complete', JSON.stringify(taskStates));
        })
        task.on('headerReceive', (headers) => {
            console.error('image-header', JSON.stringify(headers));
        })
        task.on('fail', (taskStates: Array<request.TaskState>) => {
            console.error('image-fail', JSON.stringify(taskStates));
        });
    })
}

更多关于HarmonyOS 鸿蒙Next中上传本地相册中的图片,怎么实现呢? POST请求的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复
看着是 config 中的 files 参数中的 uri 设置的有问题,把 uri 设置成 `internal://cache/upload_status_image.jpeg` 试试呢,因为 context.cacheDir 对应的就是上传文件时的 `internal://cache` 这个路径,所以不需要再拼接了

更多关于HarmonyOS 鸿蒙Next中上传本地相册中的图片,怎么实现呢? POST请求的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


不好使,上传图片不一样,需要,设置multibody,

在HarmonyOS(鸿蒙Next)中,上传本地相册中的图片可以通过以下步骤实现:

  1. 选择图片:使用@ohos.file.picker模块中的PhotoViewPicker来选择相册中的图片。PhotoViewPicker允许用户从相册中选择一张或多张图片。
import picker from '@ohos.file.picker';

let photoPicker = new picker.PhotoViewPicker();
photoPicker.select().then((photoSelectResult) => {
    let uri = photoSelectResult[0]; // 获取第一张图片的URI
    // 处理选中的图片
}).catch((err) => {
    console.error('Failed to select photo:', err);
});
  1. 读取图片数据:使用@ohos.file.fs模块读取图片文件的数据。
import fs from '@ohos.file.fs';

let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
let fileStat = fs.statSync(uri);
let buffer = new ArrayBuffer(fileStat.size);
fs.readSync(file.fd, buffer);
fs.closeSync(file);
  1. 上传图片:使用@ohos.net.http模块发起POST请求,将图片数据上传到服务器。
import http from '@ohos.net.http';

let httpRequest = http.createHttp();
let options = {
    method: http.RequestMethod.POST,
    header: {
        'Content-Type': 'multipart/form-data'
    },
    extraData: {
        'file': buffer
    }
};
httpRequest.request('https://your-server-url/upload', options, (err, data) => {
    if (err) {
        console.error('Failed to upload image:', err);
    } else {
        console.log('Image uploaded successfully:', data.result);
    }
});

以上代码展示了如何在HarmonyOS中选择、读取和上传本地相册中的图片。确保在config.json中声明相应的权限和模块依赖。

在HarmonyOS鸿蒙Next中,通过POST请求上传本地相册图片,可以按照以下步骤实现:

  1. 获取图片路径:使用@ohos.file.picker模块选择图片,获取图片的URI。
  2. 读取图片数据:使用@ohos.file.fs模块读取图片的二进制数据。
  3. 构建请求体:将图片数据放入FormData对象中。
  4. 发送POST请求:使用@ohos.net.http模块发送POST请求,将FormData作为请求体上传。

确保在config.json中声明必要的权限,如ohos.permission.READ_MEDIAohos.permission.INTERNET

参考官方文档获取具体API使用细节。

回到顶部