我知道我的问题已被多次解决,但我找不到任何可以帮助我解决具体问题的内容。
我打算从系统中的任何位置选择一个文件:
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
我在这里发现了这个 Intent :
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
}
我有一个像这样的上传方法:
private void upload(File file){
RequestParams params = new RequestParams();
try {
params.put("fileToUpload", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://...", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
System.out.println("statusCode "+statusCode);//statusCode 200
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
问题是我不知道如何“结合” onActivity 和 upload 这两个方法,因为我不知道如何处理从 Intent 中获取的信息以便 AsyncHttpClient 可以使用它。
我尝试将 Uri 转换为绝对路径,但无法管理(在线解决方案似乎专门针对图像)。我也无法将 uri“转换”为文件。
有什么办法可以做到这一点吗?我错过了什么吗?
最佳答案
理想的解决方案是使用ContentResolver
和openInputStream()
获得 InputStream
关于 Uri
标识的内容,然后传递 InputStream
到您的 HTTP 客户端 API 以用于上传。
如果您的 HTTP 客户端 API 不支持使用 InputStream
或者可以从其中派生的东西(例如 Reader
),因此您需要一个 File
,使用 InputStream
和一个 FileOutputStream
在您控制的某些文件上以制作内容的本地副本(例如,在 getCacheDir()
中)。然后,使用本地副本进行文件上传操作,并在完成后删除本地副本。
关于java - 选择用于异步 http 文件上传的文件(uri 到文件路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41838943/