可以参考一下上传下载demo:https://gitee.com/harmonyos_samples/upload-and-down-load
也可以参考一下这个代码片段:
import request from '[@ohos](/user/ohos).request';
import picker from '[@ohos](/user/ohos).file.picker';
import fs, { ReadOptions } from '[@ohos](/user/ohos).file.fs';
import common from '[@ohos](/user/ohos).app.ability.common';
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let cacheDir = context.cacheDir;
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index4 {
private openPhotoPicker() {
let photoPicker = new picker.PhotoViewPicker();
photoPicker.select({
MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
maxSelectNumber: 1
}, (error, result) => {
if (result) {
result.photoUris.forEach((uri) => {
let file = fs.openSync(uri, fs.OpenMode.CREATE);
// 复制文件到缓存目录下
fs.copyFileSync(file.fd, cacheDir + '/test.jpeg')
this.uploadImage(['internal://cache/test.jpeg']);
})
}
});
}
private uploadImage(paths: string[]) {
let allFiles = Array<request.File>()
let header = new Map<Object, string>();
header.set('Content-Type', 'multipart/form-data');
header.set('key2', 'value2');
for (let i = 0; i <paths.length; i++) {
allFiles[i] = {
name: "image" + i + ".jpeg",
filename: "image" + i + ".jpeg",
uri: paths[i],
type: "image"
}
}
let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
let uploadConfig: request.UploadConfig = {
url: 'http://XXX"',
header: header,
method: 'POST',
files: allFiles,
data: data
}
try {
request.uploadFile(getContext(this), uploadConfig, (error, uploadTask) => {
if(uploadTask) {
uploadTask.on('progress', (uploadedSize: number, totalSize: number) => {
console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
})
} else {
console.log("upload failure: " + error)
}
});
} catch (error) {
console.log("upload failure: " + error)
}
}
}
可以通过on('headerReceive')订阅上传任务HTTP响应事件responsehttps://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5#onheaderreceive7