Java 文件在使用Uri创建后为空-改型
我正在尝试使用Uri创建一个文件。但当检查它是否为空时,发现它为空。下面是Uri存储在变量“filePath”中的代码 因此,我创建了一个函数,使用改装库将文件上载到服务器。 单击按钮,调用该函数。代码如下:Java 文件在使用Uri创建后为空-改型,java,android,file,retrofit2,Java,Android,File,Retrofit2,我正在尝试使用Uri创建一个文件。但当检查它是否为空时,发现它为空。下面是Uri存储在变量“filePath”中的代码 因此,我创建了一个函数,使用改装库将文件上载到服务器。 单击按钮,调用该函数。代码如下: private void uploadFile(Uri fileUri) { String descriptionString = "hello"; File file = new File(fileUri.getPath()); if(
private void uploadFile(Uri fileUri) {
String descriptionString = "hello";
File file = new File(fileUri.getPath());
if(file.exists())
{
Toast.makeText(MainActivity.this,file.getPath(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,file.getName(),Toast.LENGTH_SHORT).show();
}
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
MultipartBody.Part image =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call<ImageResponse> call = RetrofitClient.getInstance().getApi().uploadImage(descriptionString,image);
call.enqueue(new Callback<ImageResponse>() {
@Override
public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
ImageResponse imageResponse = response.body();
if (imageResponse.isError())
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ImageResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void上传文件(Uri fileUri){
字符串描述String=“hello”;
File File=新文件(fileUri.getPath());
if(file.exists())
{
Toast.makeText(MainActivity.this,file.getPath(),Toast.LENGTH_SHORT.show();
}
其他的
{
Toast.makeText(MainActivity.this,file.getName(),Toast.LENGTH_SHORT.show();
}
请求体请求文件=
RequestBody.create(
parse(getContentResolver().getType(fileUri)),
文件
);
多部分体。部分图像=
MultipartBody.Part.createFormData(“image”,file.getName(),requestFile);
Call Call=reformationclient.getInstance().getApi().uploadImage(descriptionString,image);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
ImageResponse ImageResponse=response.body();
if(imageResponse.isError())
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT.show();
}
其他的
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT.show();
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
所以我的请求失败了,因为文件不存在。原因可能是什么?我正在使用emulator,并已添加所有必需的权限。我不知道为什么它不起作用。请帮帮我!我是新装修的
我的舱单:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我在吐司中得到的最后回应是:
文件/图像:31(无此类文件或目录)
问题是,无论您在清单中指定权限,都必须在运行时从Android v6.0检查权限。所以,您所要做的就是在运行时检查权限 这是代码。使用以下代码:
//Check Permissions on runtime
public boolean checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
(Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialog("External storage", context,
Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
ActivityCompat
.requestPermissions(
(Activity) context,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void showDialog(final String msg, final Context context,
final String permission) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage(msg + " permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[] { permission },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do your stuff
} else {
Toast.makeText(MainActivity.this, "GET_ACCOUNTS Denied",
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
//End permission code
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
filePath=data.getData();
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadFile(Uri fileUri) {
String descriptionString = "hello";
File file=FileUtils.getFile(getApplicationContext(),fileUri);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
MultipartBody.Part image =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call<ImageResponse> call = RetrofitClient.getInstance().getApi().uploadImage(descriptionString,image);
call.enqueue(new Callback<ImageResponse>() {
@Override
public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
ImageResponse imageResponse = response.body();
if (imageResponse.isError())
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ImageResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
//检查运行时的权限
公共布尔值checkPermissionREAD\u外部存储(
最终上下文(上下文){
int currentAPIVersion=Build.VERSION.SDK\u int;
if(currentAPIVersion>=android.os.Build.VERSION\u CODES.M){
if(ContextCompat.checkSelfPermission)(上下文,
Manifest.permission.READ(外部存储)!=PackageManager.permission(已授予){
如果(ActivityCompat.shouldShowRequestPermissionRegulation)(
(活动)背景,
清单.权限.读取(外部存储){
showDialog(“外部存储”,上下文,
清单。权限。读取(外部存储);
}否则{
活动公司
.requestPermissions(
(活动)背景,
新字符串[]{Manifest.permission.READ_EXTERNAL_STORAGE},
我的权限、请求、读取、外部存储);
}
返回false;
}否则{
返回true;
}
}否则{
返回true;
}
}
public void showDialog(最终字符串消息、最终上下文、,
最终字符串权限){
AlertDialog.Builder alertBuilder=新建AlertDialog.Builder(上下文);
alertBuilder.setCancelable(真);
alertBuilder.setTitle(“需要许可”);
alertBuilder.setMessage(消息+“需要权限”);
alertBuilder.setPositiveButton(android.R.string.yes,
新建DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
ActivityCompat.requestPermissions((活动)上下文,
新字符串[]{permission},
我的权限、请求、读取、外部存储);
}
});
AlertDialog alert=alertBuilder.create();
alert.show();
}
@凌驾
公共无效onRequestPermissionsResult(int requestCode,
字符串[]权限,int[]grantResults){
开关(请求代码){
案例我的权限请求读取外部存储:
if(grantResults[0]==已授予PackageManager.权限){
//做你的事
}否则{
Toast.makeText(MainActivity.this,“拒绝获取您的帐户”,
吐司。长度(短)。show();
}
打破
违约:
super.onRequestPermissionsResult(请求代码、权限、,
格兰特结果);
}
}
//结束权限代码
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==PICK\u IMAGE\u REQUEST&&resultCode==RESULT\u OK&&data!=null&&data.getData()!=null){
试一试{
如果(检查许可读取外部存储(本)){
filePath=data.getData();
位图=MediaStore.Images.Media.getBitmap(getContentResolver(),filePa
//Check Permissions on runtime
public boolean checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
(Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialog("External storage", context,
Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
ActivityCompat
.requestPermissions(
(Activity) context,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void showDialog(final String msg, final Context context,
final String permission) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage(msg + " permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[] { permission },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do your stuff
} else {
Toast.makeText(MainActivity.this, "GET_ACCOUNTS Denied",
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
//End permission code
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
filePath=data.getData();
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadFile(Uri fileUri) {
String descriptionString = "hello";
File file=FileUtils.getFile(getApplicationContext(),fileUri);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
MultipartBody.Part image =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call<ImageResponse> call = RetrofitClient.getInstance().getApi().uploadImage(descriptionString,image);
call.enqueue(new Callback<ImageResponse>() {
@Override
public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
ImageResponse imageResponse = response.body();
if (imageResponse.isError())
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ImageResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
public class FileUtils {
//replace this with your authority
public static final String AUTHORITY = "com.ianhanniballake.localstorage.documents";
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
/**
* @return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
public static boolean isLocalStorageDocument(Uri uri) {
return AUTHORITY.equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
* @author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
* @author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
* @author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* 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.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
* @see #isLocal(String)
* @see #getFile(Context, Uri)
*/
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)) {
// LocalStorageProvider
if (isLocalStorageDocument(uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Convert Uri into File, if possible.
*
* @return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* @author paulburke
* @see #getPath(Context, Uri)
*/
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
}