path (/xxx/xxx.mp4) to realpath error: No such file or directory
Common:{ThrowError:72} {ParseFileUri:<private>} ThrowError errCode:13900002 errMsg:no such file 可以确认错误原因为“/xxx/xxx.mp4”这个文件不存在。
// 虽然判断了视频文件是否存在,但是没有对不存在的情况做任何处理 const isExist = fs.accessSync(this.videoPath); const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context); // 当视频文件不存在时,执行此处代码就会报错:“No such file or directory” const assetChangeRequest = photoAccessHelper.MediaAssetChangeRequest.createVideoAssetRequest(this.context, this.videoPath); await phAccessHelper.applyChanges(assetChangeRequest);
import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import { BusinessError } from '@ohos.base';
import { PromptAction, UIContext } from '@kit.ArkUI';
@Entry
@Component
struct VideoSavePage {
private context: Context | undefined = this.getUIContext().getHostContext();
private videoPath: string = `${this.context!.filesDir}/output.mp4`;
uiContext: UIContext = this.getUIContext();
promptAction: PromptAction = this.uiContext.getPromptAction();
async saveVideo() {
// 判断文件是否存在
let isExist: boolean;
try {
isExist = fs.accessSync(this.videoPath); // 不存在会返回 false
} catch (e) {
isExist = false;
}
if (isExist) {
try {
const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context);
// 构造保存请求(视频)
const assetChangeRequest =
photoAccessHelper.MediaAssetChangeRequest.createVideoAssetRequest(this.context, this.videoPath);
// 提交到相册
await phAccessHelper.applyChanges(assetChangeRequest);
this.promptAction.showToast({ message: '已保存到相册' });
} catch (err) {
const error = err as BusinessError;
console.error(`保存失败:${error.code} ${error.message}`);
this.promptAction.showToast({ message: '保存失败,请检查权限' });
}
} else {
this.promptAction.showToast({ message: '视频文件不存在' });
}
}
build() {
Column({ space: 40 }) {
Button('保存视频到相册')
.onClick(() => this.saveVideo());
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center);
}
}