-
Notifications
You must be signed in to change notification settings - Fork 186
04 文件模块
本地文件访问及处理服务 注意插件文件处理皆处于插件沙盒目录下
Export: public
Doc_name: 文件模块
Doc_index: 4
Doc_directory: host
Example
//给定文件名后下载或者截图后被放到本地目录里, 在<Image/>等标签需要引用时, 使用{local:"filename"}的方式引入
const myfile = "testpicture.png"
Host.file.downloadFile("http://..../...png", myfile)
.then(res=>{
const myimg = <Image source={{local:myfile}} ... />
...
})
.catch(err=>{...})
...
const myshotfile = "testshot.png"
Host.file.screenShot(myshotfile)
.then(res=>{
const myshotpic = <Image source={{local:myshotfile}} ... />
...
});
...
-
miot/host/file
-
~IFile
- .storageBasePath
-
.readFileList() ⇒
Promise
-
.isFileExists(fileName) ⇒
[ 'Promise' ].<boolean>
-
.readFile(fileName, [opt]) ⇒
[ 'Promise' ].<String>
-
.readFileToHexString(fileName) ⇒
Promise
-
.readFileToBase64(fileName) ⇒
Promise
-
.readFileSegmentToBase64(fileName, off, len) ⇒
Promise
-
.writeFile(fileName, utf8Content) ⇒
Promise
- .saveFileToNotesAppOnMIUI(fileName)
-
.writeFileThroughBase64(fileName, fileContent) ⇒
Promise
-
.appendFile(fileName, utf8Content) ⇒
Promise
-
.appendFileThroughBase64(fileName, fileContent) ⇒
Promise
-
.deleteFile(fileName) ⇒
Promise
- .generateObjNameAndUrlForFDSUpload(did, suffix)
- .generateObjNameAndUrlForFDSUploadV3(did, suffix)
- .generateObjNameAndUrlForLogFileFDSUpload(did, suffix)
- .getFDSFileInfoWithObjName(obj_name)
- .getFDSFileInfoWithObjNameV3(obj_name)
-
.uploadFile(params) ⇒
Promise
-
.uploadFileToFDS(params) ⇒
Promise
-
.downloadFile(url, fileName, params) ⇒
Promise
-
.cancelDownloadFile(taskID) ⇒
Promise
-
.dataLengthOfBase64Data(base64Data) ⇒
Promise
-
.subBase64DataOfBase64Data(base64Data, loc, len) ⇒
Promise
-
.unzipFile(fileName) ⇒
Promise
-
.ungzipFileToString(params) ⇒
[ 'Promise' ].<json>
-
.ungzFile(fileName) ⇒
Promise
-
.ungzYunMiFile(fileName) ⇒
Promise
-
.saveImageToPhotosAlbum(fileName) ⇒
Promise
-
.saveFileToPhotosAlbum(fileName) ⇒
Promise
-
.saveImageToPhotosDidAlbum(fileName, customDirName) ⇒
Promiste
-
.saveVideoToPhotosDidAlbum(fileName, customDirName) ⇒
Promise
-
.fetchLocalVideoFilePathFromDidAlbumByUrl(url, customDirName) ⇒
Promise
-
.getAllSourceFromPhotosDidAlbum(customDirName) ⇒
Promise
-
.getAlbums() ⇒
Promise
-
.getAssets(albumID) ⇒
Promise
-
.deleteAssetsFromAlbumByUrls(urls) ⇒
Promise
-
.screenShot(imageName) ⇒
[ 'Promise' ].<string>
-
.screenShotInRect(imageName, rect) ⇒
[ 'Promise' ].<string>
-
.longScreenShot(viewRef, imageName) ⇒
[ 'Promise' ].<string>
-
.amapScreenShot(viewRef, imageName) ⇒
Promise
-
.getRGBAValueFromImageAtPath(imagePath, points) ⇒
Promise
-
.mkdir(params) ⇒
[ 'Promise' ].<json>
-
.queryFile(params) ⇒
[ 'Promise' ].<json>
-
.writePdfFile(utf8Content, filename, params) ⇒
[ 'Promise' ].<Object>
-
.pdfToImage(params) ⇒
[ 'Promise' ].<json>
-
.readPdfMetaData(params) ⇒
[ 'Promise' ].<json>
-
.copyFile(params) ⇒
[ 'Promise' ].<json>
-
.getStorageInfo() ⇒
[ 'Promise' ].<json>
- .cropImage(targetFileName, sourceFilename, params:)
-
~FileEvent :
object
-
~IFile
Kind: inner interface of miot/host/file
-
~IFile
- .storageBasePath
-
.readFileList() ⇒
Promise
-
.isFileExists(fileName) ⇒
[ 'Promise' ].<boolean>
-
.readFile(fileName, [opt]) ⇒
[ 'Promise' ].<String>
-
.readFileToHexString(fileName) ⇒
Promise
-
.readFileToBase64(fileName) ⇒
Promise
-
.readFileSegmentToBase64(fileName, off, len) ⇒
Promise
-
.writeFile(fileName, utf8Content) ⇒
Promise
- .saveFileToNotesAppOnMIUI(fileName)
-
.writeFileThroughBase64(fileName, fileContent) ⇒
Promise
-
.appendFile(fileName, utf8Content) ⇒
Promise
-
.appendFileThroughBase64(fileName, fileContent) ⇒
Promise
-
.deleteFile(fileName) ⇒
Promise
- .generateObjNameAndUrlForFDSUpload(did, suffix)
- .generateObjNameAndUrlForFDSUploadV3(did, suffix)
- .generateObjNameAndUrlForLogFileFDSUpload(did, suffix)
- .getFDSFileInfoWithObjName(obj_name)
- .getFDSFileInfoWithObjNameV3(obj_name)
-
.uploadFile(params) ⇒
Promise
-
.uploadFileToFDS(params) ⇒
Promise
-
.downloadFile(url, fileName, params) ⇒
Promise
-
.cancelDownloadFile(taskID) ⇒
Promise
-
.dataLengthOfBase64Data(base64Data) ⇒
Promise
-
.subBase64DataOfBase64Data(base64Data, loc, len) ⇒
Promise
-
.unzipFile(fileName) ⇒
Promise
-
.ungzipFileToString(params) ⇒
[ 'Promise' ].<json>
-
.ungzFile(fileName) ⇒
Promise
-
.ungzYunMiFile(fileName) ⇒
Promise
-
.saveImageToPhotosAlbum(fileName) ⇒
Promise
-
.saveFileToPhotosAlbum(fileName) ⇒
Promise
-
.saveImageToPhotosDidAlbum(fileName, customDirName) ⇒
Promiste
-
.saveVideoToPhotosDidAlbum(fileName, customDirName) ⇒
Promise
-
.fetchLocalVideoFilePathFromDidAlbumByUrl(url, customDirName) ⇒
Promise
-
.getAllSourceFromPhotosDidAlbum(customDirName) ⇒
Promise
-
.getAlbums() ⇒
Promise
-
.getAssets(albumID) ⇒
Promise
-
.deleteAssetsFromAlbumByUrls(urls) ⇒
Promise
-
.screenShot(imageName) ⇒
[ 'Promise' ].<string>
-
.screenShotInRect(imageName, rect) ⇒
[ 'Promise' ].<string>
-
.longScreenShot(viewRef, imageName) ⇒
[ 'Promise' ].<string>
-
.amapScreenShot(viewRef, imageName) ⇒
Promise
-
.getRGBAValueFromImageAtPath(imagePath, points) ⇒
Promise
-
.mkdir(params) ⇒
[ 'Promise' ].<json>
-
.queryFile(params) ⇒
[ 'Promise' ].<json>
-
.writePdfFile(utf8Content, filename, params) ⇒
[ 'Promise' ].<Object>
-
.pdfToImage(params) ⇒
[ 'Promise' ].<json>
-
.readPdfMetaData(params) ⇒
[ 'Promise' ].<json>
-
.copyFile(params) ⇒
[ 'Promise' ].<json>
-
.getStorageInfo() ⇒
[ 'Promise' ].<json>
- .cropImage(targetFileName, sourceFilename, params:)
沙盒路径
Kind: instance property of IFile
读取沙盒内文件列表, 返回文件的名称和文件的大小, 注意文件夹大小为:-1, 大小单位为B(字节); 从10047起,新增 modifyTime 字段:文件保存时的时间戳,单位秒
- @param {string} subFolder 读取沙盒文件夹下某子文件夹中文件内容,用于解压缩文件中带有文件夹,或者读取指定文件夹解压后的文件,标准path结构,不以'/'开头
Kind: instance method of IFile
Returns: Promise
- 成功时:[{name:'xxx', size: 'xxx' , 'modifyTime': xxx(文件保存时的时间戳,单位秒)}, {name:'xxx', size: 'xxx', 'modifyTime': xxx(文件保存时的时间戳,单位秒)}, ...] 数组的形式返回数组
失败时:result: {"code":xxx, "message":"xxx" }
Example
import {Host} from 'miot'
...
Host.file.readFileList().then(res => {
console.log('read fiel list:', res)
}).catch((isOk, result)=>{
console.log(isOk, result)
});
Host.file.readFileList('mysubfolder/aaa').then(res => {
console.log('read fiel list:', res)
})
判断文件是否存在
Kind: instance method of IFile
Returns: [ 'Promise' ].<boolean>
- 成功时:直接返回true or false
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
Example
import {Host} from 'miot'
...
let fileExist = await Host.file.isFileExists('fileName')
//or
Host.file.isFileExists('fileName').then(res => {
console.log('file exist at path:', res)
}).catch(err => {
// file name error or get file path with error
})
读本地文件, 读取普通字符串, 与之对应的写文件为Host.file.writeFile(fileName, content)
Kind: instance method of IFile
Returns: [ 'Promise' ].<String>
- 成功时:直接返回文件内容
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Default | Description |
---|---|---|---|
fileName | string |
文件名,可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' | |
[opt] | json |
{} |
其他设置项 |
Example
import {Host} from 'miot'
...
Host.filereadFile('name').then(content =>{
console.log('file content:', content)
})
读本地文件, 通常用于读取蓝牙设备需要的文件数据
Kind: instance method of IFile
Returns: Promise
- 成功时:直接返回文件内容
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
Example
import {Host} from 'miot'
...
Host.filereadFileToHexString('name').then(content =>{
console.log('file content:', content)
})
读文件,并转换为 Base64 编码
Kind: instance method of IFile
Returns: Promise
- 成功时:直接返回文件内容
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
读取一定字节的文件,并转换为 Base64 编码
Kind: instance method of IFile
Returns: Promise
- 成功时:{content:"xxx",totalLength:xxx},
content为读取到的经过Base64编码后的文件内容,类型为string
totalLength为文件总长度,类型为number
失败时:{"code":xxx, "message":"xxx" }
Since: 10045
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
off | number |
在文件中读取数据的起始位置的偏移 |
len | number |
读取的最大字节数 |
写文件, 与之对应的读文件为Host.file.readFile(fileName)
Kind: instance method of IFile
Returns: Promise
- 成功时:直接返回true
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
utf8Content | string |
文件内容字符串 |
Example
import {Host} from 'miot'
...
Host.filewriteFile('name', 'content').then(_ =>{
//写入成功
console.log('write success')
})
...
Kind: instance method of IFile
Since: 10051
保存文件内容到小米便签,仅支持特定的model
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
Example
let extra = 'test_data.txt';
Host.ui.saveFileToNotesAppOnMIUI(fileName).then((isSuccess) => {
}).catch((error) => {
});
写文件,输入为 Base64 编码的字符串, api内部会对字符串做 Base64 解码后存放到文件中
Kind: instance method of IFile
Returns: Promise
- 成功时:直接返回true
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
fileContent | string |
需要写入的文件内容 |
Example
import {Host} from 'miot'
...
Host.filewriteFileThroughBase64('name', 'base64').then(_ =>{
//写入成功
console.log('write success')
})
...
向已存在的文件追加内容, 通常是通过使用writeFile接口来写的文件
Kind: instance method of IFile
Returns: Promise
- 成功时:直接返回true
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
utf8Content | string |
文件内容字符串 |
Example
import {Host} from 'miot'
...
Host.fileappendFile('name', 'base64').then(_ =>{
//写入成功
console.log('write success')
})
...
向已存在的文件追加内容,输入为 Base64 编码的字符串, api内部会对字符串做 Base64 解码后存放到文件中
Kind: instance method of IFile
Returns: Promise
- 成功时:直接返回true
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
fileContent | string |
需要写入的文件内容 |
Example
import {Host} from 'miot'
...
Host.fileappendFileThroughBase64('name', 'base64').then(_ =>{
//写入成功
console.log('write success')
})
...
删除文件
Kind: instance method of IFile
Returns: Promise
- 成功时:直接返回true
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
Example
import {Host} from 'miot'
...
Host.filedeleteFile('name').then(_ =>{
console.log('delete success')
})
...
上传普通文件,需要申请权限使用 获取用于上传FDS文件的obj_name以及用于上传的url 访问接口:/home/genpresignedurl
Kind: instance method of IFile
Since: 10004
Param | Type | Description |
---|---|---|
did | string |
设备did |
suffix | string |
文件后缀 例如 'mp3', 'txt' |
Example
let did = Device.deviceID;
let suffix = "mp3";
Host.file.generateObjNameAndUrlForFDSUpload(did, suffix).then(res => {
if (res.hasOwnProperty(suffix) && res[suffix]) {
let obj = res[suffix];
let obj_name = obj.obj_name;
let name = obj_name.substring(obj_name.length - 22)
let content = "AC";
let time = obj.time;
this.file_obj_name = obj_name;
console.log("pre upload", res)
Host.file.writeFile(name, content).then(r => {
let param = {
uploadUrl: obj.url,
method: obj.method,
headers: { "Content-Type": "" },
files: [{ filename: name }]
}
Host.file.uploadFileToFDS(param).then(rr => {
alert('上传成功' + JSON.stringify(rr))
console.log('upload file success', rr)
}).catch(err => {
alert('上传失败' + JSON.stringify(err))
console.log('upload file failed', err)
})
}).catch(err => {
alert('存储临时文件失败' + JSON.stringify(err))
console.log("write file failed", err)
})
}
})
上传普通文件,需要申请权限使用,V3版本 获取用于上传FDS文件的obj_name以及用于上传的url 访问接口:/v2/home/genpresignedurl_v3
Kind: instance method of IFile
Since: 10056
Param | Type | Description |
---|---|---|
did | string |
设备did |
suffix | string |
文件后缀 例如 'mp3', 'txt' |
Example
let did = Device.deviceID;
let suffix = "mp3";
*** Host.file.uploadFileToFDS(param) param = {headers: { "Content-Type": "application/octet-stream" }},上传FDS需要配置Content-Type
Host.file.generateObjNameAndUrlForFDSUploadV3(did, suffix).then(res => {
if (res.hasOwnProperty(suffix) && res[suffix]) {
let obj = res[suffix];
let obj_name = obj.obj_name;
let name = obj_name.substring(obj_name.length - 22)
let content = "AC";
let time = obj.time;
this.file_obj_name = obj_name;
console.log("pre upload", res)
Host.file.writeFile(name, content).then(r => {
let param = {
uploadUrl: obj.url,
method: obj.method,
headers: { "Content-Type": "application/octet-stream" },
files: [{ filename: name }]
}
Host.file.uploadFileToFDS(param).then(rr => {
alert('上传成功' + JSON.stringify(rr))
console.log('upload file success', rr)
}).catch(err => {
alert('上传失败' + JSON.stringify(err))
console.log('upload file failed', err)
})
}).catch(err => {
alert('存储临时文件失败' + JSON.stringify(err))
console.log("write file failed", err)
})
}
})
上传日志文件。 具体使用参考generateObjNameAndUrlForFDSUpload
Kind: instance method of IFile
Since: 10011
Param | Type | Description |
---|---|---|
did | string |
|
suffix | string |
string or array |
获取FDS文件的信息,包含下载地址等信息
对于手动上传到fds的文件(没有genObjName ,在平台端直接上传的),可直接设置成public,生成url。插件端需要用这个文件时,用通用下载接口下载此url即可。 getFDSFileInfoWithObjName,这个接口只是用来下载通过插件接口(Host.file.uploadFileToFDS)上传到FDS的文件 访问接口:/home/getfileurl
Kind: instance method of IFile
Since: 10004
Param | Type | Description |
---|---|---|
obj_name | string |
generateObjNameAndUrlForFDSUpload 生成的 obj_name |
Example
let did = Device.deviceID;
let suffix = "mp3";
let file_obj_name = this.file_obj_name //从服务端获取或者本地获取,通过generateObjNameAndUrlForFDSUpload 生成
if (file_obj_name) {
Host.file.getFDSFileInfoWithObjName(file_obj_name).then(res => {
console.log('getfileurl success', res)
alert('获取成功' + JSON.stringify(res))
}).catch(err => {
console.log('getfileurl failed', err)
})
} else {
alert("先上传文件")
}
获取FDS文件的信息,包含下载地址等信息 V3版本
对于手动上传到fds的文件(没有genObjName ,在平台端直接上传的),可直接设置成public,生成url。插件端需要用这个文件时,用通用下载接口下载此url即可。 getFDSFileInfoWithObjNameV3,这个接口只是用来下载通过插件接口(Host.file.uploadFileToFDS)上传到FDS的文件 访问接口:/v2/home/getfileurl_v3
Kind: instance method of IFile
Since: 10056
Param | Type | Description |
---|---|---|
obj_name | string |
generateObjNameAndUrlForFDSUploadV3 生成的 obj_name |
Example
let did = Device.deviceID;
let suffix = "mp3";
let file_obj_name = this.file_obj_name //从服务端获取或者本地获取,generateObjNameAndUrlForFDSUploadV3 生成
if (file_obj_name) {
Host.file.getFDSFileInfoWithObjNameV3(file_obj_name).then(res => {
console.log('getfileurl success', res)
alert('获取成功' + JSON.stringify(res))
}).catch(err => {
console.log('getfileurl failed', err)
})
} else {
alert("先上传文件")
}
上传文件
Kind: instance method of IFile
Param | Type | Description |
---|---|---|
params | UploadParams |
参数字典 |
Example
import {Host} from 'miot'
...
let params = {
uploadUrl: 'http://127.0.0.1:3000',
method: 'POST', // default 'POST',support 'POST' and 'PUT'
headers: {
'Accept': 'application/json',
},
fields: {
'hello': 'world',
},
files: [
{
filename: 'fileName.png', // 必选, 只能上传插件sandbox里的文件
range: {start: 10, length: 100} // 可选, since 10037, 从start开始读取lengt长度的文件,可选,不配置则表示文件从头到尾
formdata: {name: 'name1.png', filename: 'customFileName.png'} // 可选, since 10038, 用于自定义formdata中的name和filename
},
]
};
Host.file.uploadFile(params).then(res => {
console.log('upload success with res:', res)
}).catch(err => {
console.log('upload failed with err:', err)
})
...
上传文件到小米云FDS
Kind: instance method of IFile
Param | Type | Description |
---|---|---|
params | UploadParams |
参数字典 |
Example
same as Host.file.uploadFile
下载文件到插件沙盒目录, 文件下载完成后才会回调,只支持下载单个文件
Kind: instance method of IFile
Returns: Promise
- 成功时:{header:{}, path:xxx, filename:xxx,status:xxx}
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Default | Description |
---|---|---|---|
url | string |
文件地址 | |
fileName | string |
存储到本地的文件名 | |
params | DownloadParams |
|
参数字典 可选 since 10038 |
Example
import {Host} from 'miot'
...
Host.file.downloadFile('url', 'targetName').then(res =>{
console.log('download success with res:', res)
}).catch(err => {
console.log('download failed with err:', err)
})
...
取消指定的下载任务
Kind: instance method of IFile
Returns: Promise
- 成功时:{code:0, data:{}}
失败时:{code:-1, message:'xxx'}
Param | Type | Description |
---|---|---|
taskID | string |
since 10038 下载任务的唯一ID, 与 downloadFile 传入的 taskID 一致 |
获取 base64 编码的数据长度
Kind: instance method of IFile
Returns: Promise
- 返回具体的长度
Param | Type | Description |
---|---|---|
base64Data | string |
base64 编码的字符串 |
Example
import {Host} from 'miot'
...
let len = await Host.file.dataLengthOfBase64Data('data')
//or
Host.file.dataLengthOfBase64Data('data').then(len => console.log('len:', len))
...
获取一个data的子data(base64编码)
Kind: instance method of IFile
Param | Type | Description |
---|---|---|
base64Data | string |
base64 编码的数据 |
loc | number |
起始位置 |
len | number |
长度 |
解压缩一个zip文件,解压缩后的文件会直接存储在插件存储空间的根目录下
Kind: instance method of IFile
Returns: Promise
- 成功时:返回true
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名(插件存储空间内的文件) * @param {string} desitinationPath - 目标解压缩文件夹,默认解压到当前文件夹,如果指定名称,压缩包内容会解压到指定文件夹 |
解压缩一个gzip文件为指定格式的字符串;文件首先被解压为一个字节数组,然后将字节数组转换为string(string可以是utf-8、base-64、16进制)
Kind: instance method of IFile
Returns: [ 'Promise' ].<json>
- 成功时返回:{code:0,data:'xxxxxxxxxxx'}
失败时返回:
{code:-1,message:’${fileName} is not valid’}
{code:-2,message:’${fileName} is not exist‘}
{code:-3,message:’${fileName} is not a file}
{code:-4,message: 'unzipToString failed:internal error'}
Since: 10054
Param | Type | Description |
---|---|---|
params | json |
{ fileName: 'cache/test.zip', //沙盒内的相对路径,必填 charsetName:'[utf-8 |
Example
let params = {
fileName: 'cache/test.zip',
charsetName: 'base-64',
}
Host.file.ungzipFileToString(params).then(res=>{
console.log("file content:",res);
}).catch(err=>{
console.log("ungzipFileToString error:",err);
})
解压缩一个gz文件, 并以base64编码的形式直接返回给插件, 不做本地存储
Kind: instance method of IFile
Returns: Promise
- 成功时:返回文件的内容
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
文件名(插件存储空间内的文件) |
为云米扫地机的地图文件解压提供,私有
Kind: instance method of IFile
Param | Type | Description |
---|---|---|
fileName | string |
文件名(插件存储空间内的文件) |
保存指定照片文件到系统相册
Kind: instance method of IFile
Returns: Promise
- 成功时:返回true
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
fileName | string |
可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
import {Host} from 'miot'
...
Host.file.saveImageToPhotosAlbum('name').then(_ =>{
console.log('successful save to PhotosAlbum')
})
...
保存指定文件到系统相册
Kind: instance method of IFile
Returns: Promise
- 成功时:返回true
失败时:{"code":xxx, "message":"xxx" }
Since: 10037
Param | Type | Description |
---|---|---|
fileName | string |
可以是多重文件夹嵌套文件, e.g 'path/path2/filename.txt' |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
保存指定图片文件到以did命名的相册中 该方法会在系统相册中创建一个以did[-customDirName]命名的相册(如果不存在),并将图片保存在其中
Kind: instance method of IFile
Returns: Promiste
- 成功时:返回true
失败时:
{"code":-401, "message":"access to photo library denied" }
{"code":-1, "message":"did cannot be empty" }
{"code":-2, "message":"did cannot be empty" }
{"code":-3, "message":"path is ilegal or file not exist" }
{"code":-5, "message":"filepath cannot convert to a image, please check" }
{"code":-100, "message":"failed to save image" }
{"code":-101, "message":"failed to create album" }
Since: 10037
Param | Type | Default | Description |
---|---|---|---|
fileName | string |
图片在沙盒中的文件名 | |
customDirName | string |
null |
自定义相册名称,默认为null,since 10042 |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
保存指定照片文件到以did命名的相册中 该方法会在系统相册中创建一个以did命名的相册(如果不存在),并将视频保存在其中
Kind: instance method of IFile
Returns: Promise
- 成功时:返回true
失败时:
{"code":-401, "message":"access to photo library denied" }
{"code":-1, "message":"did cannot be empty" }
{"code":-2, "message":"did cannot be empty" }
{"code":-3, "message":"path is ilegal or file not exist" }
{"code":-4, "message":"filepath cannot seek to be video file" }
{"code":-6, "message":"file cannot save to album as a video" }
{"code":-100, "message":"failed to save video" }
{"code":-101, "message":"failed to create album" }
Since: 10037
Param | Type | Default | Description |
---|---|---|---|
fileName | string |
||
customDirName | string |
null |
自定义相册名称,默认为null, since 10042 |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
从did命名的相册中 通过url获取视频文件的filepath
Kind: instance method of IFile
Returns: Promise
- 成功时:返回true
失败时:
{"code":-401, "message":"access to photo library denied" }
{"code":-1, "message":"did cannot be empty" }
{"code":-2, "message":"did cannot be empty" }
{"code":-3, "message":"url cannot be empty" }
Since: 10037
Param | Type | Default | Description |
---|---|---|---|
url | string |
||
customDirName | string |
null |
自定义相册名称,默认为null, since 10042 |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
获取指定以did命名的相册中所有的图片和视频 如果不存在该相册,返回空数组
Kind: instance method of IFile
Returns: Promise
- 成功时:{"code":0, "data":[] }
返回图片和视频信息
ios 返回 图片scheme协议 miotph:// 视频scheme miotvideo://
android 返回图片和视频文件的fileurl
每个图片信息包含key
{'url':<'miotph://XXXXXX'(ios) 'file://XXXXXX' (android)>,
'mediaType' : , // 0 : unknowntype, 1: image, 2:video, 3: audio(10037暂不支持)
'pixelWidth' :, // width信息,0 代表unknown
'pixelHeight' :, // height 0 代表unknown
'creationDate' :, // 创建时间信息,unix时间戳
'modificationDate' : , // 修改时间信息, unix时间戳
'duration' : , // 持续时间 信息 图片文件返回0 单位ms 10042之前ios返回的是秒,安卓返回的是ms 在10042 之后ios修正为ms
'uti' : , // 资源类型 since 10050 参考 https://zh.wikipedia.org/wiki/%E7%BB%9F%E4%B8%80%E7%B1%BB%E5%9E%8B%E6%A0%87%E8%AF%86
}
失败时:
{"code":-401, "message":"access to photo library denied" }
{"code":-1, "message":"did cannot be empty" }
{"code":-2, "message":"did cannot be empty" }
Since: 10037
Param | Type | Default | Description |
---|---|---|---|
customDirName | string |
null |
自定义相册名称,默认为null, since 10042 |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
获取所有相册列表, 仅支持部分设备,使用前需申请权限
Kind: instance method of IFile
Returns: Promise
- 成功时:{"code":0, "data":[] }
所有相册信息
每个相册信息包含key
{
'albumID': , // 相册唯一 ID,用于获取区别唯一相册
'thumb' : , // 与 getAllSourceFromPhotosDidAlbum 中成功返回 data 数组元素一致
'name' : , // 相册名
'size' :, // 相册中元素个数
}
失败时:
{"code":-401, "message":"access to photo library denied" }
{"code":-2, "message":"model has no permission to access photo library" }
Since: 10050
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
获取指定相册中所有的图片和视频
Kind: instance method of IFile
Returns: Promise
- 成功时:与 getAllSourceFromPhotosDidAlbum 成功时一致
失败时:
{"code":-401, "message":"access to photo library denied" }
{"code":-1, "message":"albumID is not valid" }
{"code":-2, "message":"model has no permission to access photo library" }
Since: 10050
Param | Type | Description |
---|---|---|
albumID | string |
相册唯一 ID |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
在相册中通过url 删除指定的assets
Kind: instance method of IFile
Returns: Promise
- 成功时:返回true
失败时:
{"code":-401, "message":"access to photo library denied" }
{"code":-1, "message":"did cannot be empty" }
{"code":-2, "message":"did cannot be empty" }
{"code":-3, "message":"urls cannot be parsed to a Array or it is empty" }
{"code":-100, "message":"delete assets failed" }
Since: 10037
Param | Type |
---|---|
urls | array |
Example
参考com.xiaomi.demo Host-->PhotoDemo.js
屏幕全屏截图
Kind: instance method of IFile
Returns: [ 'Promise' ].<string>
- - 截图成功回调函数返回存储图片的绝对路径,加载图片时直接使用即可
成功时:返回图片的路径
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
imageName | string |
图片名称,png, |
Example
<Image source={{local:imageName, scale:PixelRatio.get()}} />
自定义范围的屏幕截图
Kind: instance method of IFile
Returns: [ 'Promise' ].<string>
- - 截图成功 返回图片地址
成功时:返回图片的路径
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
imageName | string |
图片名称,png |
rect | Object |
截屏范围 |
长截屏,用来截scrollView,会把超出屏幕的部分也截到
Kind: instance method of IFile
Returns: [ 'Promise' ].<string>
- 成功时:返回图片的路径
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
viewRef | number |
scrollView的引用 |
imageName | string |
图片名称,png |
Example
var findNodeHandle = require('findNodeHandle');
var myScrollView = findNodeHandle(this.refs.myScrollView);
Host.file.longScreenShot(myScrollView, 'test2.png').then(imagePath=>{
console.log(imagePath);
});
高德地图截屏
Kind: instance method of IFile
Returns: Promise
- 成功时:返回图片的路径
失败时:{"code":xxx, "message":"xxx" }
Param | Type | Description |
---|---|---|
viewRef | number |
MAMapView(MHMapView的父类)的引用 |
imageName | string |
图片名称,自动添加后缀png |
Example
const findNodeHandle = require('findNodeHandle');
const myMapViewRef = findNodeHandle(this.refs.myMapView);
const imageName = 'mapToShare.png';
let imageToShow = null;
Host.file.amapScreenShot(myMapViewRef, imageName).then(() => {
imageToShow = <Image source={{local:imageName}}>
console.log("ok");
});
获取图片指定点的色值, 传空数组将返回所有点的色值
Kind: instance method of IFile
Param | Type | Description |
---|---|---|
imagePath | string |
图片文件路径 |
points | [ 'Array' ].<{x:int, y:int}> |
位置数组 |
创建目录
Kind: instance method of IFile
Returns: [ 'Promise' ].<json>
- 成功时:{code:0,message:'success'},
失败时可能的返回值有:{code:-1,message:'directory name is not valid'},
{code:-2,message:'file
Since: 10042
Param | Type | Description |
---|---|---|
params | json |
{dirPath:‘xxx’,//本地路径如:dir0,/dir0/dir1 recursive: [true/false],//是否递归创建目录。如果为 true,则创建该目录和该目录下的所有子目录 } |
Example
let params ={
dirPath: 'dir0/dir1',
recursive: true,
};
Host.file.mkdir(params)
.then(res=>{alert(JSON.stringify(res))})
.catch(err=>{alert(JSON.stringify(err))})
搜索文件(只在Android可使用)
Kind: instance method of IFile
Returns: [ 'Promise' ].<json>
- 返回值:
成功时:{ code:0,
data:[{
relativePath:'相对路径',
name:'文件名',
url:'文件地址'
size: xxx//'文件大小',
modifacationDate:xxxxx,//上次修改时间
}]
}
失败时:{
code:-xxx,
message:'xxxxx'
}
Since: 10052
Param | Type | Description |
---|---|---|
params | json |
{ mimeTypes:[],//需要搜索的文件类型 pageSize: xxx,//分页大小,number类型(如100);如果需要分页,pageSize必须大于0,不传或者传0表示不分页 pageNum: xxx,//分页编号,number类型(如0,1,2...),pageSize大于0时有效 } mimeType的可选值如下: ["application/pdf",//pdf "application/msword",//word "application/vnd.openxmlformats-officedocument.wordprocessingml.document",//docx "application/vnd.ms-excel",//xls,xlt "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",//xlsx "application/vnd.ms-powerpoint",//ppt,pot,pps "application/vnd.openxmlformats-officedocument.presentationml.presentation",//pptx "text/text",//text "text/html",//html "text/xml",//xml "image/jpeg",] |
Example
let params = {
mimeTypes: ["application/pdf", // pdf
"application/msword", // word
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", // docx
"application/vnd.ms-excel", // xls,xlt
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // xlsx
"application/vnd.ms-powerpoint", // ppt,pot,pps
"application/vnd.openxmlformats-officedocument.presentationml.presentation", // pptx
],
pageSize: 2,
pageNo: 0
};
Host.file.queryFile(params).then((res) => {
alert(JSON.stringify(res));
}).catch((err) => {
alert(JSON.stringify(err));
});
将 utf8Content 转成 PDF 文件
Kind: instance method of IFile
Returns: [ 'Promise' ].<Object>
- 成功时: {code:0, data: filepath} 绝对路径,可直接用于展示
失败时: {
code:100xx, // 错误码,非0数字
message:"" // 错误信息
}
Since: 10054
Param | Type | Description |
---|---|---|
utf8Content | string |
需要被转换的文本内容 |
filename | string |
存储为的文件名,与 isFileExists 相同 |
params | json |
样式参数 |
params.color | string |
文本颜色 如 '#FFF', 'red' |
params.fontSize | number |
字体大小 |
params.pageSize | object |
页面大小 如 {width: 200, height:100} |
params.marginHorizontal | string |
水平边距 |
params.marginVertical | string |
竖直边距 |
将PDF指定页转换为图片
Kind: instance method of IFile
Returns: [ 'Promise' ].<json>
- 成功时返回如下:
{
code:0,
data:{
imageName: 'xxxxx',//图片名称,imageDir +'/' + imageName即为图片的路径
}
}
失败是返回如下:
{code:-1,message:'invalid srcPath or imageDir'}
{code:-2,message:'no permission to access source file'}
{code:-3,message:'password required or incorrect password'}
{code:-4,message:'out of memory,set highQuality=false can reduce memory cost'}
{code:-5,message:'genarate image failed'}
{code:-6,message:'write image failed'}
{code:-7,message:'invalid input params pageIndex'}
Since: 10052
Param | Type | Description |
---|---|---|
params | json |
{ srcPath:'xxxxx',//pdf文件路径 imageDir:'xxxx',//转换后的图片保存目录(目录名,不含文件名) pageIndex: xx(如:1),//需要将PDF的那一页转换为图片,从0开始 password:'xxxxx',//PDF密码,如果没有加密传空即可 highQuality: true/false,//是否需要高质量图片:如果为true图片格式为ARGB_8888,反之为RGB565;高质量图片会占用更多的内存和磁盘 } |
Example
let params = {
mimeTypes: ["application/pdf", // pdf
],
pageSize: 1,
pageNo: 0
};
Host.file.queryFile(params).then((res) => {
if(res && res.data){
let pdf_params ={
srcPath:res.data[0].url,
imageDir: 'pdf_image',
pageIndex: 0,
password:'',
highQuality:false,
}
Host.file.pdfToImage(pdf_params).then(res=>{
alert(JSON.stringify(res));
}).catch(res=>{
alert(JSON.stringify(res));
})
}
}).catch((err) => {
alert(JSON.stringify(err));
});
读PDF文件信息
Kind: instance method of IFile
Returns: [ 'Promise' ].<json>
- 成功时返回如下:
{
code:0,
data:{
pageCount: xxx(如:30),//PDF的总页数
}
}
失败是返回如下:
{code:-1,message:'invalid srcPath or imageDir'}
{code:-2,message:'no permission to access source file'}
{code:-3,message:'password required or incorrect password'}
Since: 10052
Param | Type | Description |
---|---|---|
params | json |
{ srcPath:'xxxxx',//pdf文件路径 password:'xxxxx',//PDF密码,如果没有加密传空即可 } |
Example
Host.file.queryFile(params).then((res) => {
if(res && res.data){
let pdf_params ={
srcPath:res.data[0].url,
password:'',
}
Host.file.readPdfMetaData(pdf_params).then(res=>{
alert(JSON.stringify(res));
}).catch(res=>{
alert(JSON.stringify(res));
})
}
}).catch((err) => {
alert(JSON.stringify(err));
});
复制文件 since 10048
Kind: instance method of IFile
Returns: [ 'Promise' ].<json>
- 成功时:{code:0,message:success}
失败时:{code:-1,message:'invalid srcPath or dstPath'}
{code:-2,message:'file ${dstPath} already exist'}
{code:-3,message:'file not found,xxx'}
{code:-4,message:'copy file error,xxx'}
{code:-5,message:'copy file error,detail: create file error'}
Param | Type | Description |
---|---|---|
params | json |
{ srcPath:'xxxxx',//源文件文件路径 dstPath:'xxxx', //目标文件路径:dstDir不为空时,可以传相对路径;dstDir不为空时,这里传文件名 dstDir:'xxx',//目标文件保存路径父目录,沙盒内复制文件时传空即可;如果是往沙盒外复制,dstDiir传目标文件的父目录(不能为空) } |
Example
沙盒内复制
let copy_params={
srcPath:'test.pdf',
dstPath:'test_copy.pdf',
}
Host.file.copyFile(copy_params).then((res) => {
alert(JSON.stringify(res));
Host.file.readFileList('').then(res=>{
alert(JSON.stringify(res))
})
}).catch((res) => {
alert(JSON.stringify(res));
});
沙盒外复制
let copy_params={
srcPath:'test.pdf',
dstPath:'test_copy.pdf',
dstDir:'content://xxxxxxx'
}
Host.file.copyFile(copy_params).then((res) => {
alert(JSON.stringify(res));
Host.file.readFileList('').then(res=>{
alert(JSON.stringify(res))
})
}).catch((res) => {
alert(JSON.stringify(res));
});
获取当前磁盘的可用空间和总存储空间 since 10048
Kind: instance method of IFile
Returns: [ 'Promise' ].<json>
- 返回当前磁盘的可用空间和总存储空间:{code: 0 ,data: { totalSpace: 123456, freeSpace: 23456} },
其中totalSpace:总存储空间;freeSpace:剩余可用空间;单位都字节(byte)
Example
Host.file.getStorageInfo().then(res=>{
alert(JSON.stringify(res))
}).catch(err=>{
alert(JSON.stringify(err));
});
裁剪图片 since 10054
Kind: instance method of IFile
Returns{promise<string>}: 成功时返回裁剪后的图片路径,失败返回 {code:-1,message:'xxx'}
Param | Type | Description |
---|---|---|
targetFileName | string |
裁剪后生成的文件的文件名, 可以是多重文件夹嵌套文件, e.g 'path/path2/filename.jpg' |
sourceFilename | string |
要裁剪的源图片名 |
params: | Object |
裁剪参数 |
params.offset: | Object |
裁剪图像的左上角坐标,在原始图像的坐标空间中指定. e.g :{x:0,y:0} type int |
params.size: | Object |
裁切后的图像的尺寸,在原始图像的坐标空间中指定. e.g :{width:400,height:400} type int |
params.displaySize: | Object |
将裁切后的图像缩放到指定大小(Optional). e.g :{width:200,height:200} type int |
文件事件名集合
Kind: inner namespace of miot/host/file
文件下载时的进度事件通知
Kind: static property of FileEvent
Param | Description |
---|---|
filename | 文件名 |
url | 下载地址 |
totalBytes | 下载总大小 |
downloadBytes | 已下载文件大小 |
文件上传时的进度事件通知, 支持Host.file.uploadFile 和 Host.file.uploadFileToFDS 文件上传接口进度回调
Kind: static property of FileEvent
Param | Description |
---|---|
uploadUrl | 上传地址 |
totalBytes | 上传总大小 |
uploadBytes | 已上传文件大小 |