android 中 webview 上传图片后,图片文件失去后缀的问题

在webview中选择图片一般是设置WebChromeClient,然后重写openFileChooser方法,最后在onActivityResult中得到图片Uri

问题来了,这个Uri一般都没有文件后缀(.jpg.png),像下面这样

filecontent://media/external/images/media/68987

将图片上传到服务器后,保存在服务器的文件名字就是68987了,文件没有后缀,将后缀改为.jpg之后,图片是正确的,,,

遇到这个问题排查了一天

解决方式

根据 Uri 获取文件的真实路径, 然后再把真实路径转成 Uri. 这时候的 Uri 就是带文件真实名和后缀的.
// 根据 Uri 获取文件真实路径的代码:
https://gist.github.com/atearsan/1f0846e6dcdb3d8f3d1d

// 真实路径转成 Uri 的代码: Uri.fromFile(new File(filePath));
// Uri 打印结果: file:///storage/emulated/0/DCIM/Camera/IMG_20151006_193049.jpg


// 根据 Uri 获取文件真实路径的代码





package com.atearsan.util;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;


// Code taken from: http://stackoverflow.com/questions/20067508/get-real-path-from-uri-android-kitkat-new-storage-access-framework
public class MediaUtility {
    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     * @author paulburke
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值