index.uts 2.2 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
import {
    API_OPEN_DOCUMENT
} from '../protocol.uts'
import {
    OpenDocumentFail,
    OpenDocumentSuccess,
    OpenDocumentOptions,
    OpenDocument
} from '../interface.uts'
import {
    getAbilityContext
} from '@dcloudio/uni-runtime'
import fileUri from '@ohos.file.fileuri';
import Want from '@ohos.app.ability.Want';
import wantConstant from '@ohos.app.ability.wantConstant';
import common from '@ohos.app.ability.common';

export {
    OpenDocumentFail,
    OpenDocumentSuccess,
    OpenDocumentOptions,
}

function getContentType(filePath: string, fileType?: string | null): string | void {
    const suffix = fileType || filePath.split('.').pop();
    if (!suffix) {
        return;
    }
    switch (suffix) {
        case 'doc':
        case 'docx':
            return 'application/msword';
        case 'xls':
        case 'xlsx':
            return 'application/vnd.ms-excel';
        case 'ppt':
        case 'pptx':
            return 'application/vnd.ms-powerpoint';
        case 'pdf':
            return 'application/pdf';
        default:
            return;
    }
}

export const openDocument: OpenDocument = defineAsyncApi<OpenDocumentOptions, OpenDocumentSuccess>(
    API_OPEN_DOCUMENT,
    function (options: OpenDocumentOptions, exec: ApiExecutor<OpenDocumentSuccess>) {
        const filePath = options.filePath
        const uri = fileUri.getUriFromPath(filePath.replace(/^file:\/\//, ''));
        const fileContentType = getContentType(filePath, options.fileType);
        if (!fileContentType) {
            exec.reject('file type not supported');
            return
        }
        const want: Want = {
            flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_PERSISTABLE_URI_PERMISSION,
            action: 'ohos.want.action.sendData',
            uri: uri,
            type: fileContentType as string
        }
        const abilityContext = getAbilityContext() as common.UIAbilityContext
        abilityContext.startAbility(want).then(() => {
            exec.resolve({} as OpenDocumentSuccess)
        }, (err: Error) => {
            exec.reject(err.message);
        })
    }
) as OpenDocument