HarmonyOS鸿蒙Next中deleteToTrash(uri: string): Promise<string>接收使用约束是什么,我使用该接口删除应用沙箱中文件失败
HarmonyOS鸿蒙Next中deleteToTrash(uri: string): Promise<string>接收使用约束是什么,我使用该接口删除应用沙箱中文件失败 参照教程,无法删除下载目录下文件报错如下Failed to delete the file to trash, errMessage:{“code”:1014000001}
删除应用沙箱路径中文件,报401错误码
- filePath = /data/storage/el1/bundle/electron/resources/resfile/resources/app/my_file.txt沙箱路径存在
- 调用uri = fileUri.getUriFromPath(filePath)将其转换为URI格式file://com.huawei.ohos_electron/data/storage/el1/bundle/electron/resources/resfile/resources/app/my_file.txt
- 调用fileManagerService.deleteToTrash(uri)报错errMessage:{“code”:401}
更多关于HarmonyOS鸿蒙Next中deleteToTrash(uri: string): Promise<string>接收使用约束是什么,我使用该接口删除应用沙箱中文件失败的实战教程也可以访问 https://www.itying.com/category-93-b0.html
尊敬的开发者,您好,
fileManagerService.deleteToTrash:此接口参数uri的具体使用方式参见用户文件uri介绍中的文档类URI的使用方式,用于删除公共目录的文件到回收站。而fileUri.getUriFromPath获取的是文件uri,而不是上述接口公共目录下的文档类uri,传参uri不对就会出现报错。
如果您想要删除沙箱路径的文件,可以参考fileIo.unlink:删除文件的应用沙箱路径下的单个文件。
示例代码如下:
import { fileIo, fileIo as fs } from '@kit.CoreFileKit';
import type { common } from '@kit.AbilityKit';
import type { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct RawfileToSandbox {
context = this.getUIContext().getHostContext() as common.UIAbilityContext;
@State filePath: string = '';
build() {
Column() {
Button('复制resFile目录下文件夹到沙箱目录')
.height(100)
.width('50%')
.onClick(async () => {
let context = getContext(this) as common.UIAbilityContext;
try {
// 1. 读取rawfile下的文件内容
let val: Uint8Array = context.resourceManager.getRawFileContentSync('massage.txt');
// 2. 确定沙箱目标路径
let pathDir: string = context.filesDir; // /data/storage/el2/base/haps/entry/files
this.filePath = pathDir + '/massage.txt';
// 3. 创建并写入文件
let file = fs.openSync(this.filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeLen = fs.writeSync(file.fd, val.buffer as ArrayBuffer);
fs.closeSync(file);
console.info('File copied to sandbox successfully.');
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
console.error(`Failed to copy rawfile, error code: ${code}, message: ${message}.`);
}
});
Button('删除沙箱内文件').onClick(() => {
fileIo.unlink(this.filePath).then(() => {
console.info(`Succeeded in removing file.`);
}).catch((err: BusinessError) => {
console.error(`Failed to remove file. Code: ${err.code}, message: ${err.message}`);
});
});
}
.height(300)
.width('100%')
.justifyContent(FlexAlign.SpaceAround);
}
}
更多关于HarmonyOS鸿蒙Next中deleteToTrash(uri: string): Promise<string>接收使用约束是什么,我使用该接口删除应用沙箱中文件失败的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
我的诉求是把参数表里的“待删除文件的 uri”再收窄一点,建议写成“待删除公共目录文件的文档类 URI”,并在注意事项里明确应用沙箱路径不适用。
现在示例代码实际用的是 file://docs/storage/Users/currentUser/Download/1.txt,这已经体现了公共目录/文档类 URI;但参数说明只写“待删除文件的 uri”,开发者很容易把 /data/storage/el*/base/files、cacheDir、filesDir 这类应用沙箱文件也传进去。
可以补一句:若删除应用沙箱内文件,请使用 fileIo.unlink/unlinkSync 等文件 API;deleteToTrash 面向公共目录文件进入系统回收站的场景,不用于应用私有沙箱文件。这样和示例、错误码 1014000001 的理解会更一致。
这里的关键点是 deleteToTrash 面向的是“公共目录文件进系统回收站”,不是应用沙箱文件。你用它删除应用沙箱中的文件失败,方向上基本是符合预期的。FileManagerServiceKit 文档示例里的 URI 是公共目录形态,例如 Download 下的 file://docs/storage/Users/currentUser/Download/1.txt。
如果文件在应用沙箱,比如 filesDir/cacheDir 下,建议直接使用文件 API 删除,不走系统回收站:
import { fileIo as fs } from '@kit.CoreFileKit';
const path = getContext(this).filesDir + '/test.txt';
await fs.unlink(path);
如果确实要删除公共目录文件,则要确认三件事:URI 是公共目录 URI,不是沙箱 path;文件真实存在;当前应用已经获得对应文件的读写授权。
import { fileManagerService } from '@kit.FileManagerServiceKit';
const targetUri = 'file://docs/storage/Users/currentUser/Download/1.txt';
const trashUri = await fileManagerService.deleteToTrash(targetUri);
console.info('moved to trash: ' + trashUri);
所以排查时建议先打印 uri/path:沙箱路径用 fileIo 处理,公共目录 URI 才交给 fileManagerService.deleteToTrash,二者不要混用。
参考文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/filemanagerservice-deletetotrash
建议更新开发指导文档,明确使用场景和使用约束
尊敬的开发者,您好,根据您提供的如上链接场景介绍已经明确说明:删除公共目录的文件到回收站。已表明fileManagerService.deleteToTrash接口中uri需要传参为待删除公共目录文件的uri。
您是想要此接口fileManagerService.deleteToTrash中uri参数说明为待删除公共目录文件的uri?麻烦您详细描述下您具体的诉求吧(例如:xxx链接需要添加xxx说明)
看一下这里,
错误码 401:Parameter error
可能原因:
- 缺少必要参数
- 参数类型不正确
- 参数校验失败(如 URI 不是有效的公共目录文件 URI)
重要说明
该接口仅支持对公共数据目录(
/storage/media/100/local/files)下的文件进行操作,不支持应用沙箱路径。
你传入的 URI:
file://com.huawei.ohos_electron/data/storage/el1/bundle/electron/...
-
格式为应用沙箱文件 URI(
file://bundleName/...) -
不属于
file://media/...这种公共目录 URI -
直接命中错误码 401 的第三种原因(非有效的公共目录文件 URI)
-
删除沙箱文件请用
@ohos.file.fs.unlink -
deleteToTrash只能用于用户公共目录下的文件(如从文件选择器获取的下载目录文件)
1014000001 操作不允许。当前用户文件操作不被允许,URI或path访问未授权。
处理步骤
1、通过系统文件选择器(FilePicker),选择用户文件从而获取URI临时权限。
2、通过程序访问控制机制,向用户申请授权从而获取目录权限。
解决:参考 文档类URI的使用方式 通过 DocumentViewPicker 接口选择或保存文件,返回选择或保存的文件URI。
import { fileManagerService } from '@kit.FileManagerServiceKit';
import { picker } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
build() {
Column() {
Text(this.message)
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
let uris: string[] = [];
// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
// 创建文件选择器实例
let documentSelectOptions = new picker.DocumentSelectOptions
const documentViewPicker = new picker.DocumentViewPicker(context);
documentViewPicker.select(documentSelectOptions).then(async (documentSelectResult: Array<string>) => {
// 文件选择成功后,返回被选中文档的URI结果集。
uris = documentSelectResult;
let targetUri: string = uris.toString();
try {
let trashUri: string = await fileManagerService.deleteToTrash(targetUri);
console.info(`trashUri: ` + trashUri);
} catch (err) {
let error: BusinessError = err as BusinessError;
console.error(`delete failed, errCode:` + error.code + `, errMessage:` + error.message);
}
console.info(`documentViewPicker.select to file succeed and uris are:` + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
})
}
.height('100%')
.width('100%')
}
}
删除沙箱的用fileIo.unlinkSync 或 fileIo.unlink
删除设备公用目录的文件,使用fileManagerService.deleteToTrash,需要获取访问权限后调用 或
借助DocumentViewPicker:
deleteDocument() {
const documentSelectOptions = new picker.DocumentSelectOptions();
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
const documentViewPicker = new picker.DocumentViewPicker(context);
documentViewPicker.select(documentSelectOptions).then((documentSaveResult: string[]) => {
fileManagerService.deleteToTrash(documentSaveResult[0]);
}).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker failed, code is ${err.code}, message is ${err.message}`);
});
}
这个问题看起来像是 deleteToTrash() 的使用场景理解错了,不太像权限问题。
先说结论:
fileManagerService.deleteToTrash() 主要针对用户文件(公共目录文件)设计,不支持直接删除应用沙箱里的文件。你传入的是应用沙箱 URI,所以返回 401 是正常现象。
你当前的流程:
let filePath = '/data/storage/el1/bundle/electron/resources/resfile/resources/app/my_file.txt'
let uri = fileUri.getUriFromPath(filePath)
await fileManagerService.deleteToTrash(uri)
生成出来的 URI 类似:
file://com.huawei.ohos_electron/data/storage/el1/bundle/...
这是典型的应用沙箱 URI。
为什么会报 401
deleteToTrash() 的本质不是:
删除文件
而是:
移动到系统回收站
而 HarmonyOS 的回收站机制是面向用户文件体系的。
例如:
Download
Documents
Desktop
Pictures
这些公共目录里的文件。
应用沙箱目录本身就不属于系统文件管理器管理的范围,因此:
沙箱文件
↓
没有回收站概念
↓
deleteToTrash失败
就会出现 401。
1014000001 又是什么
你前面提到:
Failed to delete the file to trash
code:1014000001
这个错误通常也说明:
当前 URI 不属于 deleteToTrash 支持的资源类型。
常见情况有:
- 沙箱文件
- 非 FilePicker 获取的 URI
- 自己拼出来的 URI
- 文件已经不存在
本质上还是 URI 来源不符合接口要求。
沙箱文件正确删除方式
对于:
/data/storage/el1/...
这种路径,
直接用:
import { fileIo as fs } from '@kit.CoreFileKit'
await fs.unlink(filePath)
或者:
fs.unlinkSync(filePath)
就行。
例如:
import { fileIo as fs } from '@kit.CoreFileKit'
try {
await fs.unlink(filePath)
console.info('删除成功')
} catch (err) {
console.error(JSON.stringify(err))
}
还有一个细节
你的路径:
/data/storage/el1/bundle/electron/resources/resfile/resources/app/my_file.txt
我看到这里有点警觉。
因为:
resources
resfile
很多时候属于应用资源目录。
如果这个文件本来就是打包进 HAP 的资源文件,那么它本身就是只读的。
例如:
entry/src/main/resources/rawfile
打包后的资源文件。
这种文件:
能读
不能删
不能改
即使不用 deleteToTrash(),直接 unlink() 也会失败。
所以我觉得你应该先确认一下:
my_file.txt
到底是:
情况1
运行时创建的文件
filesDir
cacheDir
preferences目录
那就直接 unlink()。
情况2
工程资源文件
resources
rawfile
resfile
那它根本不允许删除。
从你贴出来的路径看:
/bundle/electron/resources/resfile/resources/app/
我反而更怀疑是第二种情况。这样的话别说 deleteToTrash(),任何删除接口都会失败。
应该是路径传入不对导致的;
一般通过DocumentViewPicker选择器来选择用户文件后再通过deleteToTrash去删除选择获取的路径地址uri
例如:file://docs/storage/Users/currentUser/Download/xxx.txt
沙箱文件获取的路径是 /data/storage/el2/base/xxx ,不符合当前api的 uri路径
找HarmonyOS工作还需要会Flutter的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:https://www.bilibili.com/video/BV1S4411E7LY/?p=17,
这个接口更适合删除“用户文件/文档类 URI”到系统回收站,不适合直接处理应用安装资源目录或普通沙箱路径。
文档里的示例 URI 是 file://docs/storage/Users/currentUser/Download/1.txt 这类文档类 URI,并且调用方要对该文件有读写权限。你现在的路径在 /data/storage/el1/bundle/electron/resources/…,属于应用 bundle/resource 挂载出来的资源路径,通常是只读的;用 fileUri.getUriFromPath() 转成 file://包名/… 也不会变成 File Manager Service 可删除到回收站的 docs URI,所以容易出现 401 参数校验失败或 1014000001 Operation not permitted。
建议这样分开处理:
- 如果是应用沙箱内自己生成的临时文件、缓存文件、业务文件,用 @ohos.file.fs 的 unlink/rmdir 等文件接口直接删除。
- 如果确实要进入系统回收站,先通过文件选择器、文档类 URI 或文件管理相关入口拿到 file://docs/… 形式的用户文件 URI,并确认有对应读写授权后再调用 deleteToTrash。
- 不建议把任意 /data/storage 路径手工转换成 uri 后传入 deleteToTrash,这个转换只解决 URI 表达形式,不会补齐文件管理服务所需的访问范围和权限。
deleteToTrash(uri: string): Promise<string> 仅处理媒体库或公共目录文件,URI需符合file://或content://媒体库格式。应用沙箱内文件不适用此接口,应使用fs.unlink或fs.rm删除。失败原因包括:权限不足(需ohos.permission.WRITE_DOCUMENT)、URI无效、文件被占用。
deleteToTrash 接口的设计目标是将用户可见的公共文件移入系统回收站,仅支持公共目录或通过 FilePicker 等用户选择方式获取的 URI。应用沙箱目录(如 /data/storage/el1/bundle/...)属于应用私有区域,不暴露给系统回收站服务,因此传入该 URI 会因参数无效或权限不足返回 401(Invalid argument)。
如需删除沙箱内文件,应使用 Core File Kit 提供的 fileIo.unlink 或 fileAccess.delete 等直接删除接口,这些接口不受此限制。

