取消(中断)网络任务
let downloadTask;
await ymx.downloadFile({
url: 'https://www.yimenapp.com/doc/doc.pdf',
filePath: 'fs://file/my/doc.pdf',
onNetworkTaskCreated(task) {
console.log('task', task);
downloadTask = task;
},
async onDataReceiveProgress(progress) {
console.log(`共需接收 ${progress.totalSize} Bytes,已接收 ${progress.receiveSize} Bytes`);
//下载超过 30KB 就取消,仅作为接口调用示例展示。
if (downloadTask && (progress.receiveSize > 30 * 1024)) {
await ymx.abortNetworkTask(downloadTask);
}
}
});
下载文件
await ymx.downloadFile({
url: 'https://www.yimenapp.com/doc/doc.pdf'
});
//下载保存到指定的文件路径
await ymx.downloadFile({
url: 'https://www.yimenapp.com/doc/doc.pdf',
filePath: 'fs://file/my/doc.pdf'
});
//本地临时图片文件路径
const imageFile = 'fs://temp/img.jpg';
try {
//下载图片
await ymx.downloadFile({
url: 'https://i.yimenyun.net/sys/2.jpg',
filePath: imageFile,
onNetworkTaskCreated(task) {
console.log('download task', task);
},
onDataReceiveProgress: (progress) => {
console.log(`总共 ${progress.totalSize} Bytes,已下载 ${progress.receiveSize} Bytes`);
}
});
alert('已下载,即将保存到相册。');
//保存到相册
await ymx.saveImageToPhotosAlbum({
filePath: imageFile
});
alert('已保存到相册');
} catch (err) {
alert(err.message);
} finally {
//删除临时文件
const fs = ymx.getFileSystemManager();
if (await fs.exist({ path: imageFile })) {
await fs.remove({ path: imageFile });
}
}
网络请求
//POST
await ymx.request({
url: 'https://www.yimenapp.com/doc/echo2',
method: 'POST',
data: {
key1: 'value 1',
hello: '世界'
},
onNetworkTaskCreated(task) {
console.log('request task', task);
},
onReceiveResponseHeaders: (headers) => {
console.log('服务器响应头', headers);
},
onDataSendProgress: (progress) => {
console.log(`共需发送 ${progress.totalSize} Bytes,已发送 ${progress.sendSize} Bytes`);
},
onDataReceiveProgress: (progress) => {
console.log(`共需接收 ${progress.totalSize} Bytes,已接收 ${progress.receiveSize} Bytes`);
}
});
//GET
await ymx.request({
url: 'https://www.yimenapp.com/doc/echo2',
method: 'GET'
});
上传文件
//相册选图 -> 压缩 -> 上传
try {
//从相册选图
const choose = await ymx.chooseMedia({
sourceType: ['album'],
mediaType: ['image'],
count: 1
});
const imageFile = choose.tempFiles[0]?.tempFilePath;
if (imageFile) {
//可直接上传相册原始图片
//await ymx.uploadFile({
// url: 'https://www.yimenapp.com/doc/echo2',
// filePath: imageFile
//});
const compressedImage = 'fs://temp/file-to-upload.jpg';
//压缩图片
await ymx.compressImage({
src: imageFile,
compressedWidth: 720,
quality: 85,
filePath: compressedImage
});
//上传图片
const res = await ymx.uploadFile({
url: 'https://www.yimenapp.com/doc/echo2',
filePath: compressedImage,
onNetworkTaskCreated(task) {
console.log('upload task', task);
},
onDataSendProgress: (progress) => {
console.log(`总共 ${progress.totalSize} Bytes,已上传 ${progress.sendSize} Bytes`);
}
});
alert(`已上传,服务器返回字符串:\n${res.data}`)
}
} catch (err) {
alert(`失败 ${err.message}`)
}
//上传 fs:// 本地文件
await ymx.uploadFile({
url: 'https://www.yimenapp.com/doc/echo2',
filePath: 'fs://file/my_dir/doc.pdf'
});
网络