我正在使用Android Pie中的Retrofit进行个人资料照片更改功能。
所以我成功地将用相机拍摄的照片上传到服务器。 但是我不知道如何将从图库中选择的照片传输到我的服务器。 (我对Java Kotlin中的任何代码都很好。)
我稍后再上传视频。
我在Google上搜索了很多东西,但是很难获得我想要的信息。
在Google文档中做得很好,但我不知道该怎么做。 https://developer.android.com/guide/topics/providers/document-provider
Google文档显示了使用位图或输入流之类的示例。
我需要位图或输入流才能使用翻新来上传照片吗?
我实际上需要一个有效的uri。
public void performFileSearch() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, PICTURES_DIR_ACCESS_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode,Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode ==Activity.RESULT_OK) {
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}
}
public void Edit_Profile (String Image_Uri) {
File file = new File(Image_Uri);
RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/*"));
MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", Num+ID+".jpg", requestBody);
}
实际上,onActivityResult返回以下uri类型。
content://com.android.providers.media.documents/document/image%3A191474
因此,当我尝试使用该uri将其发送到服务器时,会收到FileNotFoundException错误。
答案 0 :(得分:0)
这是Android-Q中引入的隐私限制。当某个应用程序以API 29为目标并且从getExternalStorageDirectory方法返回的路径不再可供应用程序直接访问时,不建议直接访问共享/外部存储设备。使用应用程序特定的目录来读写文件。
默认情况下,将为Android 10及更高版本的应用提供scoped access into external storage或范围存储。此类应用可以在外部存储设备中查看以下类型的文件,而无需请求任何与存储相关的用户权限:
应用程序特定目录中的文件,可使用getExternalFilesDir()访问。 该应用程序从媒体商店创建的照片,视频和音频剪辑。
浏览文档Open files using storage access framework
谈到上下文,您可以做的一件事就是 CommonsWare建议使用
InputStreamRequestBody
。否则,请复制 所选文件到应用程序沙箱文件夹IE(特定于应用程序) 目录,然后在没有任何许可的情况下从那里访问文件。 只需查看下面的可在Android-Q及更高版本中使用的实现即可。
执行文件搜索
private void performFileSearch(String messageTitle) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
intent.setType("application/*");
String[] mimeTypes = new String[]{"application/x-binary,application/octet-stream"};
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, messageTitle), OPEN_DIRECTORY_REQUEST_CODE);
} else {
Log.d("Unable to resolve Intent.ACTION_OPEN_DOCUMENT {}");
}
}
onActivityResult返回
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent resultData) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code OPEN_DIRECTORY_REQUEST_CODE.
// If the request code seen here doesn't match, it's the response to some other intent,
// and the below code shouldn't run at all.
if (requestCode == OPEN_DIRECTORY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter. Pull that uri using "resultData.getData()"
if (resultData != null && resultData.getData() != null) {
new CopyFileToAppDirTask().execute(resultData.getData());
} else {
Log.d("File uri not found {}");
}
} else {
Log.d("User cancelled file browsing {}");
}
}
}
文件写入应用特定路径
public static final String FILE_BROWSER_CACHE_DIR = "CertCache";
@SuppressLint("StaticFieldLeak")
private class CopyFileToAppDirTask extends AsyncTask<Uri, Void, String> {
private ProgressDialog mProgressDialog;
private CopyFileToAppDirTask() {
mProgressDialog = new ProgressDialog(YourActivity.this);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Please Wait..");
mProgressDialog.show();
}
protected String doInBackground(Uri... uris) {
try {
return writeFileContent(uris[0]);
} catch (IOException e) {
Log.d("Failed to copy file {}" + e.getMessage());
return null;
}
}
protected void onPostExecute(String cachedFilePath) {
mProgressDialog.dismiss();
if (cachedFilePath != null) {
Log.d("Cached file path {}" + cachedFilePath);
} else {
Log.d("Writing failed {}");
}
}
}
private String writeFileContent(final Uri uri) throws IOException {
InputStream selectedFileInputStream =
getContentResolver().openInputStream(uri);
if (selectedFileInputStream != null) {
final File certCacheDir = new File(getExternalFilesDir(null), FILE_BROWSER_CACHE_DIR);
boolean isCertCacheDirExists = certCacheDir.exists();
if (!isCertCacheDirExists) {
isCertCacheDirExists = certCacheDir.mkdirs();
}
if (isCertCacheDirExists) {
String filePath = certCacheDir.getAbsolutePath() + "/" + getFileDisplayName(uri);
OutputStream selectedFileOutPutStream = new FileOutputStream(filePath);
byte[] buffer = new byte[1024];
int length;
while ((length = selectedFileInputStream.read(buffer)) > 0) {
selectedFileOutPutStream.write(buffer, 0, length);
}
selectedFileOutPutStream.flush();
selectedFileOutPutStream.close();
return filePath;
}
selectedFileInputStream.close();
}
return null;
}
// Returns file display name.
@Nullable
private String getFileDisplayName(final Uri uri) {
String displayName = null;
try (Cursor cursor = getContentResolver()
.query(uri, null, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(
cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i("Display Name {}" + displayName);
}
}
return displayName;
}
答案 1 :(得分:0)
这是一个可能更通用的解决方案,它允许将 AsyncTask 类分开,而不是嵌入到活动中。它还在任务完成时返回对您的活动的响应,并使用 ProgressBar 而不是已弃用的 ProgressDialog。
异步任务:
public class FileLoader extends AsyncTask<Uri, Void, String>
{
private WeakReference<Context> contextRef;
public AsyncResponse delegate = null;
public interface AsyncResponse {
void fileLoadFinish(String result);
}
FileLoader(Context ctx , AsyncResponse delegate) {
contextRef = new WeakReference<>(ctx);
this.delegate = delegate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Uri... uris) {
Context context = contextRef.get();
ContentResolver contentResolver = context.getContentResolver();
Uri uri = uris[0];
try {
String mimeType = contentResolver.getType(uri);
Cursor returnCursor =
contentResolver.query(uri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String fileName = returnCursor.getString(nameIndex);
InputStream inputStream = contentResolver.openInputStream(uri);
File downloadDir =
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File f = new File(downloadDir + "/" + fileName);
FileOutputStream out = new FileOutputStream(f);
IOUtils.copyStream(inputStream,out);
returnCursor.close();
return f.getPath();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
delegate.fileLoadFinish(result);
super.onPostExecute(result);
}
}
并在您的活动中:
private static final int DIR_ACCESS_REQUEST_CODE = 13;
public void performFileSearch() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/*");
String[] mimeTypes = new String[]{"application/gpx+xml","application/vnd.google-earth.kmz"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Choose KMZ or GPX file"), DIR_ACCESS_REQUEST_CODE);
} else {
Log.d("****File","Unable to resolve Intent.ACTION_OPEN_DOCUMENT");
}
}
@Override
public void onActivityResult(int requestCode, int resultCode,Intent resultData)
{
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == DIR_ACCESS_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
if (resultData != null)
{
Uri uri = resultData.getData();
mProgressBar.setVisibility(View.VISIBLE);
new FileLoader(this,
new FileLoader.AsyncResponse(){
@Override
public void fileLoadFinish(String result){
processFile(new File(result));
mProgressBar.setVisibility(View.GONE);
}
}).execute(uri);
}
}
}
我的示例尝试查找 .kmz 文件或 .gpx 文件。需要在 OnCreate() 中初始化(并隐藏)进度条(如果需要,用于长时间运行的文件操作):
mProgressBar = findViewById(R.id.progressbar);
mProgressBar.setVisibility(View.GONE);
我的“processFile()”方法需要一段时间来操作主活动中的地图,所以我一直等到它完成后才隐藏 ProgressBar。
我仍然感到惊讶的是,执行如此简单的操作需要如此多的代码:复制文件并使其可供使用!