打开文件选择器
// 打开系统的文件选择器
public void pickFile(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
this.startActivityForResult(intent, REQUEST_CODE);
}
获取文件的真实路径
// 获取文件的真实路径
@Override
protected void onActivityResult(final int requestCode, final int resultCode, @Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null) {
// 用户未选择任何文件,直接返回
return;
}
Uri uri = data.getData(); // 获取用户选择文件的URI
// 通过ContentProvider查询文件路径
ContentResolver resolver = this.getContentResolver();
Cursor cursor = resolver.query(uri, null, null, null, null);
if (cursor == null) {
// 未查询到,说明为普通文件,可直接通过URI获取文件路径
String path = uri.getPath();
return;
}
if (cursor.moveToFirst()) {
// 多媒体文件,从数据库中获取文件的真实路径
String path = cursor.getString(cursor.getColumnIndex("_data"));
}
cursor.close();
}
使用OkHttp上传文件
// 使用OkHttp上传文件
public void uploadFile(File file) {
OkHttpClient client = new OkHttpClient();
MediaType contentType = MediaType.parse("text/plain"); // 上传文件的Content-Type
RequestBody body = RequestBody.create(contentType, file); // 上传文件的请求体
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw") // 上传地址
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// 文件上传成功
if (response.isSuccessful()) {
Log.i("Haoxueren", "onResponse: " + response.body().string());
} else {
Log.i("Haoxueren", "onResponse: " + response.message());
}
}
@Override
public void onFailure(Call call, IOException e) {
// 文件上传失败
Log.i("Haoxueren", "onFailure: " + e.getMessage());
}
});
}
网友评论