HarmonyOS 鸿蒙Next 请提供一下发送请求上传图片的demo
HarmonyOS 鸿蒙Next 请提供一下发送请求上传图片的demo 请提供一下发送请求上传图片的demo
2 回复
demo仅供参考
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import picker from '@ohos.file.picker';
import { fileIo } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
async function savePhotoToGallery(context: common.UIAbilityContext) {
let helper = photoAccessHelper.getPhotoAccessHelper(context);
try {
// onClick触发后5秒内通过createAsset接口创建图片文件,5秒后createAsset权限收回。
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
// 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
context.resourceManager.getMediaContent($r('app.media.app_icon').id, 0)
.then(async value => {
let media = value.buffer;
// 写到媒体库文件中
await fileIo.write(file.fd, media);
await fileIo.close(file.fd);
promptAction.showToast({ message: '已保存至相册!' });
});
}
catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`);
}
}
@Entry
@Component
struct IR240820142011118 {
@State message: string = '点击上传图片';
build() {
Column() {
SaveButton({
text: SaveDescription.SAVE_TO_GALLERY,
buttonType: ButtonType.Capsule,
icon: SaveIconStyle.FULL_FILLED
})
.onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
// 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
savePhotoToGallery(context);
} else {
promptAction.showToast({ message: '设置权限失败!' })
}
})
Text('selectPicture')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.selectPicture()
})
Text('选择视频')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.selectVideo()
})
}
.height('100%')
.width('100%')
}
selectPicture() {
try {
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
PhotoSelectOptions.maxSelectNumber = 2;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then(PhotoSelectResult => {
console.info('==SY==PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult.photoUris));
this.uploadImage(PhotoSelectResult.photoUris[0])
}).catch(err => {
console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
});
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
}
}
selectVideo(){
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE;
PhotoSelectOptions.maxSelectNumber = 2;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then(PhotoSelectResult => {
console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult.photoUris));
this.uploadImage(PhotoSelectResult.photoUris[0])
}).catch(err => {
console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
});
}
uploadImage(uri: string) {
const resFile = fs.openSync(uri, fs.OpenMode.READ_ONLY)
let newPath = `${getContext().cacheDir}/${resFile.name}`;
fs.copyFileSync(resFile.fd, newPath)
console.info('uri = ' + uri, 'newPath = ' + newPath)
let files: Array<request.File> = [
{ filename: resFile.name, name: 'file', uri: `internal://cache/${resFile.name}`, type: 'image/png' }
]
let header = new Map<Object, string>()
header['Content-Type'] = 'multipart/form-data'
header['bucketId'] = 'GSP_PRIVATE'
header['C-Tenancy-Id'] = '210000000000'
header['C-App-Id'] = 'GSP_APP_001'
header['C-Dynamic-Password-Foruser'] = ''
let uploadConfig: request.UploadConfig = {
url: 'http://10.234.196.126:8080/upLoadFile',
header: header,
method: 'POST',
files: files,
data: []
};
try {
request.uploadFile(getContext(), uploadConfig).then(data => {
console.error('uploadFile')
console.error(`${JSON.stringify(data)}`)
data.on('complete', taskStates => {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[0])}`);
});
data.on('headerReceive', headers => {
console.info("upOnHeader headers:" + JSON.stringify(headers));
})
data.on('fail', taskStates => {
for (let i = 0; i < taskStates.length; i++) {
console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
}
})
}).catch(err => {
console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
});
} catch (err) {
console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
}
}
}
更多关于HarmonyOS 鸿蒙Next 请提供一下发送请求上传图片的demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS(鸿蒙)系统中,发送请求上传图片的Demo可以通过使用ArkUI(基于JS或eTS框架)或者原生Java(针对特定模块,但此要求中避免使用Java)来实现。以下是一个基于ArkUI eTS框架的简单示例,用于展示如何上传图片:
@Entry
@Component
struct UploadImageDemo {
@State private imagePath: string = '';
@Builder uploadButton() {
Column() {
Button('选择图片')
.onClick(() => {
mediaLibrary.pickFile({
types: ['image/*'],
accept: (file: File) => {
this.imagePath = file.uri;
this.uploadImage(file);
}
});
})
}
}
private async uploadImage(file: File) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('https://your-server-upload-url', {
method: 'POST',
body: formData
});
const result = await response.json();
console.log('Upload result:', result);
}
build() {
Column() {
this.uploadButton()
}
}
}
此代码片段展示了如何在ArkUI中创建一个按钮来选择图片,并将其上传到服务器。注意,https://your-server-upload-url
需要替换为你的实际服务器上传地址。
如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html