HarmonyOS 鸿蒙Next 能否提供一个图片上传到服务器的完整demo
HarmonyOS 鸿蒙Next 能否提供一个图片上传到服务器的完整demo
Axios和FormData实现文件上传功能参考demo您借鉴一下
import { picker } from '@kit.CoreFileKit'
import fs from '[@ohos](/user/ohos).file.fs';
import { Context } from '@kit.AbilityKit';
import fileUri from "[@ohos](/user/ohos).file.fileuri";
import axios, { AxiosProgressEvent, AxiosRequestConfig, AxiosResponse, FormData } from '[@ohos](/user/ohos)/axios';
// import { HttpResponseModel } from ‘…/core/network/config’;
class HttpResponseModel {
}
@Entry
@Component
struct UploadPage {
@State imageUrl: string = ‘’
private context: Context = getContext(this)
async executeUpload(filename: string) {
let internalUri = internal:<span class="hljs-comment">//cache/${filename}
;
console.error(‘internal uri is:’ + internalUri)
let formData = new FormData()
formData.append(‘file’, internalUri)
//formData.append(‘type’, 1)
let request: AxiosRequestConfig<FormData> = {
url: ‘input your url’,
headers:
{
‘Accept’: ‘/’,
‘Content-Type’: ‘multipart/form-data’,
},
method: “post”,
context: this.context,
data: formData,
onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
console.error(progressEvent && progressEvent.loaded && progressEvent.total ?
Math.ceil(progressEvent.loaded / progressEvent.total * 100) + ‘%’ : ‘0%’);
}
}
try {
let resp: AxiosResponse<HttpResponseModel> =
await axios.request<HttpResponseModel, AxiosResponse<HttpResponseModel>, FormData>(request)
} catch (e) {
console.error(e)
}
}
build() {
Column() {
Image(this.imageUrl).width(100).height(100).backgroundColor(’#F00’)
Button(‘select photo from gallery’).onClick(async () => {
let photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE
photoSelectOptions.maxSelectNumber = 1
let uris: Array<string> = [];
const photoViewPicker = new picker.PhotoViewPicker()
let ctx = getContext(this)
console.error(ctx.cacheDir)
console.error(ctx.filesDir)
let photoSelectResult = await photoViewPicker.select(photoSelectOptions)
uris = photoSelectResult.photoUris;
// 也可以换成已经拿到的图库图片uri
let tmp_imageUri = uris[0]
console.error(‘select image uri:$tmp_imageUri’)
// 1. 复制文件到沙箱
fs.open(tmp_imageUri, (err, file) => {
if (err) {
console.error("file open failed with error message: " + err.message + ", error code: " + err.code);
} else {
let filename = ‘111.jpg’
let filepath = this.context.cacheDir + ‘//’ + filename;
console.error(‘filename is:’ + filename + ‘, file path is:’ + filepath)
fs.copyFile(file.fd, filepath, () => {
// /data/storage/el2/base/haps/entry/cache/111.jpg
this.imageUrl = fileUri.getUriFromPath(filepath)
// start upload task
this.executeUpload(filename)
});
}
})
})
}
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
除此之外还可用 request接口:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5
request接口通过POST上传图片文件,文件上传文件需要使用类型为 multipart/form-data提交
我理解不用吧,您可以和后端调试一下,具体报什么错误呀
其次三方库的方案不建议使用,图片上传用官网的request接口更为合适
以下是一个HarmonyOS鸿蒙Next系统中图片上传到服务器的完整demo:
// 引入必要的模块
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { request } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
// 从相册选择图片并上传
async function uploadImageFromGallery() {
const options = new photoAccessHelper.PhotoSelectOptions();
options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
options.maxSelectNumber = 1;
const picker = new photoAccessHelper.PhotoViewPicker();
picker.select(options).then(async (result) => {
if (result.photoUris.length > 0) {
const uri = result.photoUris[0];
const cachePath = `${getContext().cacheDir}/${new Date().getTime()}.jpg`;
fs.copyFileSync(fs.fileFdSync(uri), fs.fileFdSync(cachePath));
await uploadImage(cachePath);
}
}).catch((error) => {
console.error('Failed to select image:', error.message);
});
}
// 上传图片
async function uploadImage(filePath) {
const uploadConfig = {
url: 'http://your-upload-url.com',
method: 'POST',
files: [{
filename: filePath,
name: 'file',
uri: `internal://cache/${filePath}`,
type: 'image/jpeg'
}],
data: []
};
const uploadTask = await request.uploadFile(getContext(), uploadConfig);
// 处理上传进度、成功、失败等回调
}
// 调用函数上传图片
uploadImageFromGallery();
请注意替换http://your-upload-url.com
为你的实际服务器地址。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html 。