uri,file,path互相转化

本文介绍了如何在Android中实现URI与File之间的转换方法,包括从URI获取文件路径、将File转换为URI以及路径到URI的转换等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

uri转file
file = new File(new URI(uri.toString()));
uri转path:

视频uri

private String getPath(Uri uri) {  
    String[] projection = {MediaStore.Video.Media.DATA};  
    Cursor cursor = managedQuery(uri, projection, null, null, null);  
    int column_index = cursor  
         .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);  
    cursor.moveToFirst();  
    return cursor.getString(column_index);  
}

图片uri

private File uri2File(Uri uri) {  
    File file = null;  
    String[] proj = { MediaStore.Images.Media.DATA };  
    Cursor actualimagecursor = getActivity().managedQuery(uri, proj, null,  
                null, null);  
    int actual_image_column_index = actualimagecursor  
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
    actualimagecursor.moveToFirst();  
    String img_path = actualimagecursor  
         .getString(actual_image_column_index);  
    file = new File(img_path);  
    return file;  
}
  • ##### file转URI:
URI uri = file.toURI();
  • ##### file转path:
String path = file.getPath()
  • ##### path转uri:
Uri uri = Uri.parse(path);
  • ##### path转file:
File file = new File(path)
### 将 `file.url` 转换为 `file.raw` 为了将前端中的 `file.url` 转换回 `file.raw` 对象,可以利用浏览器提供的 `fetch` API 和 `Blob` 构造函数来获取原始文件数据并创建一个新的 `File` 实例。 #### 方法一:通过 Fetch 获取 Blob 并转换成 File 当拥有一个指向图片或其他资源的 URL 时,可以通过发送 HTTP 请求下载该资源的内容作为二进制数据流(即 `Blob`),再基于此构建新的 `File` 对象: ```javascript async function getUrlToFile(url, fileName) { try { const response = await fetch(url); const blobData = await response.blob(); return new File([blobData], fileName, { type: blobData.type }); } catch (error) { console.error('Failed to convert URL to File:', error); } } ``` 这种方法适用于处理来自服务器端响应或者静态资源链接的情况[^1]。 #### 方法二:使用 HTMLImageElement 加载图像并通过 canvas 提取像素数据 如果目标是一个本地存储路径或者是同源策略允许访问的数据 URI 方式的 URL,则可以直接加载到 `<img>` 标签中,并借助 Canvas 来读取其内容进而生成对应的 `Blob` 或者 `File` 对象: ```html <!-- 假设有一个 img 元素 --> <img id="target-image" src="/path/to/image.jpg"/> <script> const imageElm = document.getElementById('target-image'); imageElm.onload = async () => { // 创建画布上下文用于绘制原图 const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // 设置画布尺寸匹配图片大小 canvas.width = imageElm.naturalWidth; canvas.height = imageElm.naturalHeight; // 绘制图片至画布上 ctx.drawImage(imageElm, 0, 0); // 把画布上的内容导出为 PNG 数据URL字符串形式 const dataUrl = canvas.toDataURL(); // 解析data-url得到mime-type以及base64编码后的body部分 const mimeType = dataUrl.match(/:(.*?);/)[1]; const byteString = atob(dataUrl.split(',')[1]); // 处理byte-string转Uint8Array数组 const arrayBuffer = new ArrayBuffer(byteString.length); const uint8Array = new Uint8Array(arrayBuffer); for(let i=0;i<byteString.length;++i){ uint8Array[i]=byteString.charCodeAt(i); } // 利用Blob构造器创建新实例 const blob = new Blob([uint8Array], {type:mimeType}); // 返回最终形成的File对象 return new File([blob],"exported.png",{type:mimeType}); }; </script> ``` 这种方式更适合于操作已经存在于页面内的 DOM 结构里的图片元素[^3]。 对于 el-upload 插件而言,在成功上传之后通常会接收到包含有实际文件信息的对象,其中就包含了 `raw` 属性。因此建议尽可能保留这些原始属性而不是仅仅保存 URL 地址;但如果确实遇到了只有 URL 的情况,则可以根据上述两种方式之一来进行转换[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值