唐锦佳钰
唐锦佳钰
  • 发布:2024-02-25 23:46
  • 更新:2024-03-01 16:54
  • 阅读:395

uniapp x 文件选择后进行文档上传

分类:uni-app x

const initen_new : Intent = new Intent(Intent.ACTION_GET_CONTENT);
initen_new.setType("/");
initen_new.addCategory(Intent.CATEGORY_OPENABLE);
UTSAndroid.getUniActivity()!.startActivityForResult(initen_new, 1);
UTSAndroid.onAppActivityResult((requestCode, resultCode, data ?: Intent) => {
let REQUEST_CODE_PICK_DOCUMENT = 1;
let RESULT_OK = -1;
if (requestCode == REQUEST_CODE_PICK_DOCUMENT && resultCode == RESULT_OK && data != null) {
let selectedFileUri : Uri = data.getData()!;
console.log("Selected file URI: " + selectedFileUri);
let contentResolver = UTSAndroid.getUniActivity()?.getContentResolver()!;
let cursor = contentResolver.query(selectedFileUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
let fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
let fileSize = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));

                            /**  这怎么获取文件的真实路径   然后进行上传 */  
                        }  

                        if (cursor != null) {  
                            cursor.close();  
                        }  
                    }  
                });
2024-02-25 23:46 负责人:DCloud_Android_DQQ 分享
已邀请:
唐锦佳钰

唐锦佳钰 (作者)

怎么获取 返回的文件的真实路径用于上传文件

DCloud_Android_DQQ

DCloud_Android_DQQ

提供一下可以复现问题的最简示例。

DCloud_Android_DQQ

DCloud_Android_DQQ

看你贴的代码,在获取到 selectFileUri 之后,拼接逻辑是错误的,对应的本地地址根本不存在你期望的文件。

你可以直接把selectFileUri 传递给上传api 试试

2***@qq.com

2***@qq.com

可以参考这个 安卓10以上要把文件复制到沙盒目录下来用

function fileSelectStart(options : InfoOptions) {  
    const context = UTSAndroid.getAppContext();  
    if (context != null) {  
        const intent = new Intent(Intent.ACTION_GET_CONTENT);  
        if (options.scope != null) {  
            let strPath = options.scope;  
            strPath = strPath?.replaceAll("/", "%2F");  
            let uriByScope : Uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3A" + strPath);  
            intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriByScope);  
        }  
        intent.setType('*/*');  
        if (options.mimetype != null) {  
            switch (options.mimetype) {  
                case 'image'://图片  
                    intent.setType(IMAGE);  
                    break;  
                case 'video'://视频  
                    intent.setType(VIDEO);  
                    break;  
                case 'audio'://音频  
                    intent.setType(AUDIO);  
                    break;  
                case 'word'://文档  
                    intent.putExtra(Intent.EXTRA_MIME_TYPES, WORD.toTypedArray());  
                    break;  
                default:  
                    intent.setType(options.mimetype);  
                    break;  
            }  
        }  
        intent.addCategory(Intent.CATEGORY_OPENABLE);  
        UTSAndroid.getUniActivity()?.startActivityForResult(intent, FILE_SELECT_REQUEST_CODE);  
        UTSAndroid.onAppActivityResult((requestCode : Int, resultCode : Int, data ?: Intent) => {  
            UTSAndroid.offAppActivityResult(null);  
            if (requestCode == FILE_SELECT_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {  
                const fileUri = data.getData();  
                if (fileUri != null) {  
                    let path = getRealPathFromURI(context, fileUri);  
                    const file = new File(path);  
                    if (file.exists()) {  
                        let upLoadFilePath = file.toString();  
                        let upLoadFileName = file.getName();  
                        let fileSize = file.length();  
                        const extIdx = upLoadFileName.lastIndexOf(".");  
                        let fileExt = extIdx != -1 ? upLoadFileName.substring(extIdx + 1) : "";  
                        const res = {  
                            code: "0",  
                            filePath: upLoadFilePath,  
                            fileName: upLoadFileName,  
                            fileSize: fileSize,  
                            fileExt: fileExt,  
                            errMsg: 'fileselect:ok',  
                            detail: "文件读取成功"  
                        };  
                        options.success?.(res);  
                        options.complete?.(res);  
                    } else {  
                        const res2 = {  
                            code: "1002",  
                            errMsg: 'fileselect:fail',  
                            detail: "文件不存在"  
                        };  
                        options.fail?.(res2);  
                        options.complete?.(res2);  
                    }  
                }  
            }  
        });  
    } else {  
        const res3 = {  
            code: "1005",  
            errMsg: 'fileselect:fail',  
            detail: "文件选取出错:context为null"  
        };  
        options.fail?.(res3);  
        options.complete?.(res3);  
    }  
}  

function getRealPathFromURI(context : Context, uri : Uri) : string {  
    const isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;  
    //4.4以下的版本:不支持  
    //大于4.4   
    // DocumentProvider   
    if (isKitKat) {  
        if (DocumentsContract.isDocumentUri(context, uri)) {  
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {  
                if (isExternalStorageDocument(uri)) {  
                    console.log("isExternalStorageDocument");  
                    return saveFileFromUri(context, uri);  
                }  
                // DownloadsProvider  
                else if (isDownloadsDocument(uri)) {  
                    console.log("isDownloadsDocument");  
                    return saveFileFromUri(context, uri);  
                }  
                // MediaProvider   
                else if (isMediaDocument(uri)) {  
                    console.log("isMediaDocument");  
                    return saveFileFromUri(context, uri);  
                }  
            } else {  
                let docId = DocumentsContract.getDocumentId(uri);  
                let splits = docId.split(":");  
                let type = '';  
                let id = '';  
                if (splits.length == 2) {  
                    type = splits[0];  
                    id = splits[1];  
                }  
                if (isExternalStorageDocument(uri)) {  
                    console.log("isExternalStorageDocument")  
                    if ("primary".equals(type)) {  
                        return Environment.getExternalStorageDirectory().getAbsolutePath() as string + File.separator as string + id;  
                    } else {  
                        return "/storage/" + type + "/" + id;  
                    }  
                }  
                // DownloadsProvider  
                else if (isDownloadsDocument(uri)) {  
                    console.log("isDownloadsDocument")  
                    const downloadPath : string = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();  
                    const fileName : string = getFileName(context, uri);  
                    return downloadPath + "/" + fileName;  
                }  
                // MediaProvider   
                else if (isMediaDocument(uri)) {  
                    let externalUri : Uri | null = null;  
                    switch (type) {  
                        case "image":  
                            externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
                            break;  
                        case "video":  
                            externalUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;  
                            break;  
                        case "audio":  
                            externalUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
                            break;  
                        case "document":  
                            externalUri = MediaStore.Files.getContentUri("external");  
                            break;  
                    }  
                    if (externalUri != null) {  
                        var selection : string = "_id=?";  
                        let selectionArgs : string[] = [id];  
                        return getDataColumn(context, externalUri, selection, selectionArgs);  
                    }  
                }  
            }  
        }  
        //其他 content  
        else if ("content".equals(uri.getScheme())) {  
            // return getDataColumn(context, uri, null, null);  
            console.log("content")  
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {  
                return saveFileFromUri(context, uri);  
            } else {  
                return getDataColumn(context, uri, null, null);  
            }  
        }  
        //其他 file  
        else if ("file".equals(uri.getScheme())) {  
            console.log("file")  
            return uri.getPath() as string;  
        }  
    }  
    return ""  
}  
function isExternalStorageDocument(uri : Uri) : boolean {  
    return "com.android.externalstorage.documents".equals(uri.getAuthority());  
}  

function isDownloadsDocument(uri : Uri) : boolean {  
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
}  
function isMediaDocument(uri : Uri) : boolean {  
    return "com.android.providers.media.documents".equals(uri.getAuthority());  
}  

function getDataColumn(context : Context, uri : Uri, selection : string | null, selectionArgs : String[] | null) : string {  
    let path = uri.getPath() as string;  
    let authroity = uri.getAuthority();  
    let sdPath = Environment.getExternalStorageDirectory().getAbsolutePath() as string;  
    if (!path.startsWith(sdPath)) {  
        let sepIndex = path.indexOf(File.separator, 1);  
        if (sepIndex == -1) {  
            path = '';  
        } else {  
            path = sdPath + path.substring(sepIndex);  
        }  
    }  
    if (path == '' || !new File(path).exists()) {  
        let resolver = context.getContentResolver();  
        let projection = arrayOf<string>(MediaStore.MediaColumns.DATA);  
        const _selectionArgs = selectionArgs != null ? selectionArgs.toTypedArray() : null;  
        let cursor = resolver.query(uri, projection, selection, _selectionArgs, null);  
        if (cursor != null) {  
            if (cursor.moveToFirst()) {  
                try {  
                    var index = cursor.getColumnIndexOrThrow(projection[0]);  
                    if (index != -1) {  
                        path = cursor.getString(index);  
                    }  
                } catch (e) {  
                    console.log(e);  
                    path = '';  
                } finally {  
                    cursor?.close();  
                }  
            }  
        }  
    }  
    return path;  
}  
function getFileName(context : Context, uri : Uri) : string {  
    let projection = arrayOf(MediaStore.Images.ImageColumns.DISPLAY_NAME)  
    let cursor = context.getContentResolver().query(uri, projection, null, null, null)  
    try {  
        if (cursor != null && cursor.moveToFirst()) {  
            let name_col_index = cursor.getColumnIndex(projection[0]);  
            return cursor.getString(name_col_index);  
        }  
    } catch (e) {  
        console.log(e);  
    } finally {  
        cursor?.close()  
    }  
    return ""  
}  

function saveFileFromUri(context : Context, uri : Uri) : string {  
    let file : File;  
    const contentResolver : ContentResolver = context.getContentResolver();  
    const cursor : Cursor | null = contentResolver.query(uri, null, null, null, null);  
    if (cursor != null && cursor.moveToFirst()) {  
        const displayName = getFileName(context, uri);  
        try {  
            const is = contentResolver.openInputStream(uri);  
            if (is != null) {  
                const file1 : File = new File(context.getExternalCacheDir()?.getAbsolutePath() + "/" + System.currentTimeMillis());  
                if (!file1.exists()) {  
                    file1.mkdir();  
                }  
                const cache : File = new File(file1.getPath(), displayName);  
                const fos = new FileOutputStream(cache);  
                console.log(fos);  
                FileUtils.copy(is, fos);  
                file = cache;  
                fos.close();  
                is.close();  
                return file.getAbsolutePath();  
            }  
        } catch (e) {  
            console.log(e);  
        }  
    }  
    return ""  
}
  • 赢无翳

    你这个支持多选吗朋友?能把你这个完整的UTS插件给我研究一下吗?方便留给你联系方式吗

    2024-10-12 19:43

要回复问题请先登录注册